另一个相关问题是Segmentation fault while using strcpy()?
我有一个结构:
struct thread_data{
char *incall[10];
int syscall arg_no;
int client_socket;
}; 如何初始化指向上述类型结构的指针,以及初始化指向结构内10个字符串(incall[])的指针。
我要先初始化字符串,然后再初始化结构吗?
谢谢。
编辑:我想我用错了词,应该说是分配。实际上,我将这个结构作为参数传递给线程。不是的。线程的数量是不固定的,作为参数发送的数据结构对于每个线程必须是唯一的,并且“线程安全”,即不能被其他线程改变。
发布于 2011-06-10 02:33:59
这是我认为你在问的问题的答案:
/**
* 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的结果,以确保它是成功的。
发布于 2011-06-10 01:39:23
相应的struct初始化器可能如下所示:
struct thread_data a = {
.incall = {"a", "b", "c", "d", "e"},
.arg_no = 5,
.client_socket = 3
};然后你可以将它的地址赋值给一个指针:
struct thread_data *b = &a;发布于 2011-06-10 01:35:04
这取决于你是否需要你的变量是临时的:
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.在这两种情况下,您都必须首先分配结构才能访问它的字段。
https://stackoverflow.com/questions/6296880
复制相似问题