初始化指向结构的指针

另一个链接的问题是使用strcpy()分段错误?

我有一个结构

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

如何初始化一个指向上面types的结构的指针,并初始化结构内的10个string(incall [])的指针。

我是否首先初始化string,然后是结构。

谢谢。

编辑:我想我使用了错误的词,应该说分配。 其实我把这个结构作为parameter passing给线程。 线程数量不固定,作为参数发送的数据结构对于每个线程必须是唯一的,并且“线程安全”即不能被其他线程改变。

    以下是我想问你问题的答案:

     /** * 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的结果,以确保它成功之前,继续下一件事。

    相应的struct初始化可以像这样:

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

    然后你可以把这个地址分配给一个指针:

     struct thread_data *b = &a; 

    这取决于你是否需要你的变量是临时的:

     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. 

    在这两种情况下,您必须首先分配您的结构才能访问其字段。

    你可以这样写:

     #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); } } 

    我认为malloc(sizeof(struct thread_data)); 应该工作,不是吗?

    这是另一种可能性。 我不清楚你想要什么值初始化,所以这只是一个数字,这几乎肯定是错误的。

     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 );