Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

c - Initializing a pointer to a structure

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

I have a structure:

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

How do I initialize a pointer to a structure of type above as well as initialize the pointer to the 10 strings (incall[]) inside the structure.

Do I first initialize the strings and then the structure.

Thanks.

An edit: I guess I used the wrong word and should have said allocate. Actually I am passing this structure as an argument to threads. No. of threads is not fixed and the data structure sent as argument must be unique for each thread and "thread safe" i.e cannot be changed by other threads.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...