Initializing a pointer to a structure

前端 未结 6 2217
半阙折子戏
半阙折子戏 2020-12-18 00:32

another linked question is Segmentation fault while using strcpy()?

I have a structure:

struct thread_data{    
    char *incall[10];
    int syscall         


        
6条回答
  •  无人及你
    2020-12-18 00:56

    Here's the answer to the question I think you're asking:

    /**
     * Allocate the struct.
     */
    struct thread_data *td = malloc(sizeof *td);
    
    /**
     * Compute the number of elements in td->incall (assuming you don't
     * want to just hardcode 10 in the following loop)
     */
    size_t elements = sizeof td->incall / sizeof td->incall[0];
    
    /**
     * Allocate each member of the incall array
     */
    for (i = 0; i < elements; i++)
    {
      td->incall[i] = malloc(HOWEVER_BIG_THIS_NEEDS_TO_BE);
    }
    

    Now you can assign strings to td->incall like so:

    strcpy(td->incall[0], "First string");
    strcpy(td->incall[1], "Second string");
    

    Ideally, you want to check the result of each malloc to make sure it was successful before moving on to the next thing.

提交回复
热议问题