初始化指向结构的指针

Lip*_*eka 6 c linux structure initialization

使用strcpy()时另一个链接问题是Segmentation fault?

我有一个结构:

struct thread_data{    
    char *incall[10];
    int syscall arg_no;    
    int client_socket;
 }; 
Run Code Online (Sandbox Code Playgroud)

如何初始化指向上述类型结构的指针,以及初始化指向结构内10个字符串(incall [])的指针.

我首先初始化字符串然后初始化结构.

谢谢.

编辑:我想我使用了错误的单词,应该说是分配.实际上我传递这个结构作为线程的参数.线程数没有固定,作为参数发送的数据结构对于每个线程必须是唯一的,并且"线程安全"即不能被其他线程更改.

Joh*_*ode 12

以下是我认为你问的问题的答案:

/**
 * 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);
}
Run Code Online (Sandbox Code Playgroud)

现在您可以td->incall像这样分配字符串:

strcpy(td->incall[0], "First string");
strcpy(td->incall[1], "Second string");
Run Code Online (Sandbox Code Playgroud)

理想情况下,您需要检查每个结果malloc以确保它成功,然后再继续下一步.


Bla*_*iev 6

相应的struct初始化程序可能如下所示:

struct thread_data a = {
  .incall = {"a", "b", "c", "d", "e"},
  .arg_no = 5,
  .client_socket = 3
};
Run Code Online (Sandbox Code Playgroud)

然后你可以将它的地址分配给一个指针:

struct thread_data *b = &a;
Run Code Online (Sandbox Code Playgroud)

  • 如果这是在函数内部完成的,那么一旦函数返回,`*b`就会指向堆栈的某个地方? (7认同)
  • 是的,但程序员始终有责任确保函数退出后不再有指针指向堆栈帧中的内存。 (3认同)