Initializing a structure pointer

another related question is Segmentation error when using strcpy ()?

I have a structure:

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

How to initialize a pointer to a structure of the type above, and also initialize a pointer to 10 lines (incall []) inside the structure.

I initialize the lines first, and then the structure.

Thank.

Editing: I assume that I used the wrong word and should have said “highlight”. In fact, I pass this structure as an argument to threads. The number of threads is not fixed, and the data structure sent as an argument must be unique for each thread and "thread safe", so it cannot be changed by other threads.

+5
6

, , , :

/**
 * 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);
}

td->incall :

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

malloc, , , .

+10

struct :

struct thread_data a = {
  .incall = {"a", "b", "c", "d", "e"},
  .arg_no = 5,
  .client_socket = 3
};

:

struct thread_data *b = &a;
+4

, :

struct thread_data data; // allocated on the stack
// initialize your data.* field by field.

struct thread_data* data = malloc(sizeof (struct thread_data)); // allocated on the heap
// initialize your data->* field by field.

, .

+1

- :

#define ARRAY_DIMENSION(a) (sizeof(a)/sizeof((a)[0]))

void init_func(void)
{
    struct thread_data arg_to_thread;
    int i;
    char buffer[100];

    buffer[0] = '\0';

    for ( i = 0; i < ARRAY_DIMENSION(arg_to_thread.incall); i ++ )
    {
         /* Do something to properly fill in 'buffer' */

         arg_to_thread.incall[i] = strdup(buffer);
    } 
}
+1

I think it   malloc(sizeof(struct thread_data)); should work, right?

+1
source

Here is another opportunity. It is not clear to me that you want to initialize the values, so it just grabs a number from the air, which is almost certainly not the case.

struct thread_data *td;
int i;
// allocate memory for the structure
td = malloc( sizeof( struct thread_data ));
// then allocate/initialize the char* pointers.  It isn't clear
// what you want in them ... pointers to existing data?  Pre-allocated
// buffer?  This just allocates a fixed size buffer,
for ( i = 0; i < sizeof( td->incall ) / sizeof( td->incall[0] ); i++ )
   td->incall[i] = malloc( 42 );
+1
source

All Articles