如何正确地为 C 中的结构数组分配 malloc [英] How to properly malloc for array of struct in C

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

问题描述

我将使用 strtok 读取两组 char*(或字符串),并且由于这两组字符是相关的,(address : command\n) 我决定使用一个结构.

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*));

这一行 malloc 函数的空间给了我一个分段错误,想知道你是否可以告诉我一个正确的方法来 malloc 空间.对于上下文,这是我的其余代码:

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++;
}

推荐答案

分配对所有类型的工作方式都相同.如果你需要分配一个 line 结构的数组,你可以用:

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));

在您的代码中,您为line 指针而不是line 结构分配了一个具有适当大小的数组.另请注意,没有理由强制转换 malloc() 的返回值.

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)

代替:

sizeof(struct line)

这样做的原因是,如果您更改了 array 的类型,分配仍将按预期工作.在这种情况下,这不太可能,但这只是值得习惯的一般事情.

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.

另请注意,通过typedef对结构体进行typedef,可以避免一遍又一遍地重复struct这个词:

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;

然后你可以这样做:

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

当然不要忘记也为array.addrarray.inst 分配内存.

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

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

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