如何正确的malloc在C结构数组 [英] How to properly malloc for array of struct in C

查看:108
本文介绍了如何正确的malloc在C结构数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将分两个组使用 strtok的,而且由于这两个集的char * (或字符串)的读取的字符是相关的,。(地址:命令\\ n)我决定用一个结构

 结构行*阵列=(结构线*)malloc的(的sizeof(文件)* sizeof的(结构线*));

这行的函数malloc ING空间给了我一个分段错误,并想知道如果你能告诉我的malloc 为它的空间。上下文,这里是我的code的其余部分:

 结构线
{
    字符*地址;
    字符*研究所;
};
while循环{
    X = strtok的(行,:);
    Y =的strtok(NULL,\\ n);
    的strcpy(数组[我] .addr,X); //假设x和y是始终3characters
    的strcpy(数组[我] .inst,++ Y);
    我++;
}


解决方案

配置适用于所有类型相同。如果您需要分配结构的数组,你这样做有:

 结构行*阵列=的malloc(number_of_elements *的sizeof(结构线));

在您的code,你被分配一个数组,有适当的大小为指针,而不是为结构。另外请注意,没有理由投的返回值的malloc()

请注意这是它最好的风格是:

 的sizeof(*数组)

而不是:

 的sizeof(结构线)

这样做的原因是,随着预期的情况下,你改变的阵列类型配置仍然可以工作。在这种情况下,这是不可能的,但它是用来值得得到只是一个普通的事情。

另外请注意,有可能避免必须重复一遍这个词结构结束,并通过的typedef ING该结构:

  typedef结构线
{
    字符*地址;
    字符*研究所;
}线;

您可以再只是做:

 行*阵列=的malloc(number_of_elements * sizeof的(*数组));

当然别忘了也为 array.addr array.inst 分配内存。

I will read in two set of char* (or strings) using strtok, and since those two set of chars are related, (address : command\n) I decided to use a structure.

struct line* array = (struct line*)malloc(sizeof(file) * sizeof(struct line*));

This line mallocing space for the function gives me a segmentation fault and was wondering if you can tell me a proper way to malloc space for it. For context, here is the rest of my code:

struct line
{
    char* addr;
    char* inst;
};
while loop{
    x = strtok(line,": ");
    y = strtok(NULL,"\n");
    strcpy(array[i].addr,x); //assume that x and y are always 3characters
    strcpy(array[i].inst,++y);
    i++;
}

解决方案

Allocating works the same for all types. If you need to allocate an array of line structs, you do that with:

struct line* array = malloc(number_of_elements * sizeof(struct line));

In your code, you were allocating an array that had the appropriate size for line pointers, not for line structs. Also note that there is no reason to cast the return value of malloc().

Note that's it's better style to use:

sizeof(*array)

instead of:

sizeof(struct line)

The reason for this is that the allocation will still work as intended in case you change the type of array. In this case this is unlikely, but it's just a general thing worth getting used to.

Also note that it's possible to avoid having to repeat the word struct over and over again, by typedefing the struct:

typedef struct line
{
    char* addr;
    char* inst;
} line;

You can then just do:

line* array = malloc(number_of_elements * sizeof(*array));

Of course don't forget to also allocate memory for array.addr and array.inst.

这篇关于如何正确的malloc在C结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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