另一个相关问题是Segmentation fault while using strcpy()?
我有一个结构:
struct thread_data{
char *incall[10];
int syscall arg_no;
int client_socket;
};
如何初始化指向上述类型结构的指针,以及初始化指向结构内10个字符串(incall [])的指针。
我首先初始化字符串然后初始化结构。
感谢。
编辑:我想我使用了错误的单词,应该说是分配。实际上我传递这个结构作为线程的参数。线程数没有固定,作为参数发送的数据结构对于每个线程必须是唯一的,并且“线程安全”,即其他线程不能更改。
答案 0 :(得分:11)
以下是我认为你问的问题的答案:
/**
* 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
的结果,以确保它成功,然后再继续下一步。
答案 1 :(得分:6)
相应的struct
初始化程序可能如下所示:
struct thread_data a = {
.incall = {"a", "b", "c", "d", "e"},
.arg_no = 5,
.client_socket = 3
};
然后您可以将其地址分配给指针:
struct thread_data *b = &a;
答案 2 :(得分:2)
这取决于您是否需要将您的变量设为临时变量:
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.
在这两种情况下,您必须先分配您的结构才能访问其字段。
答案 3 :(得分: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);
}
}
答案 4 :(得分:1)
malloc(sizeof(struct thread_data));
应该工作,不是吗?
答案 5 :(得分:1)
这是另一种可能性。我不清楚你想要初始化的值是什么,所以这只是抓住一个数字,这几乎肯定是错误的。
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 );