初始化指向结构的指针 [英] Initializing a pointer to a structure

查看:125
本文介绍了初始化指向结构的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我有一个结构:

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

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

How do I initialize a pointer to a structure of type above as well as initialize the pointer to the 10 strings (incall[]) inside the structure.

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

Do I first initialize the strings and then the structure.

谢谢.

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

An edit: I guess I used the wrong word and should have said allocate. Actually I am passing this structure as an argument to threads. No. of threads is not fixed and the data structure sent as argument must be unique for each thread and "thread safe" i.e cannot be changed by other threads.

推荐答案

这是我想问的问题的答案:

Here's the answer to the question I think you're asking:

/**
 * 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:

Now you can assign strings to td->incall like so:

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

理想情况下,您要检查每个malloc的结果以确保成功后再进行下一个操作.

Ideally, you want to check the result of each malloc to make sure it was successful before moving on to the next thing.

这篇关于初始化指向结构的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆