C语言 如何正确地为 C 中的结构数组分配 malloc

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19613752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:50:27  来源:igfitidea点击:

How to properly malloc for array of struct in C

carraysstructmalloc

提问by o0tomato0o

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.

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

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 mallocspace for it. For context, here is the rest of my code:

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

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

回答by Nikos C.

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

分配对所有类型都相同。如果你需要分配一个line结构体数组,你可以这样做:

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

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

在您的代码中,您为line指针分配了一个具有适当大小的数组,而不是为line结构分配了适当的大小。另请注意,没有理由强制转换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.

这样做的原因是,如果您更改array. 在这种情况下,这不太可能,但这只是值得习惯的一般事情。

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

另请注意struct,通过typedefing 结构可以避免一遍又一遍地重复单词:

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.addrand array.inst.

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

回答by ryyker

For what you have described, You do not need to allocate memory for your struct, rather, you need to allocate memory for the members char *addr;, and char *inst;. If you want to have a single copy of that structure, the first section of code illustrates how to initialize, and assign values. If you want an array, the second code example illustrates the differences.

对于您所描述的,您不需要为 struct 分配内存而是需要为成员分配内存char *addr;, 和char *inst;。如果您想拥有该结构的单个副本,代码的第一部分说明了如何初始化和赋值。如果你想要一个数组,第二个代码示例说明了不同之处。

This illustrates how to allocate memory for the members of a single struct line:

这说明了如何为单个结构行的成员分配内存

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

LINE line;  

int main(void)
{   

    strcpy(line.addr, "anystring"); //will fail
    line.addr = malloc(80);
    line.inst = malloc(80);
    strcpy(line.addr, "someString");//success;
    strcpy(line.inst, "someOtherString");//success;

}

For array of struct line...

对于结构线数组...

typedef struct
{
    char* addr;
    char* inst;
}LINE;  //same struct definition

LINE line[10]; //but create an array of line here.

int main(void)
{   
    int i;

    for(i=0;i<10;i++)
    {
      line[i].addr = malloc(80);
      line[i].inst = malloc(80);
    }

    for(i=0;i<10;i++)
    {
        strcpy(line[i].addr, "someString");
        strcpy(line[i].inst, "someOtherString");
    }
    //when done, free memory
    for(i=0;i<10;i++)
    {
        free(line[i].addr);
        free(line[i].inst);
    }      


}