简体   繁体   English

指向结构的指针和数组的 malloc memory

[英]Pointer to a Pointer to a Structure and malloc memory for array

I'm creating a pointer to a pointer to a structure to create a dynamic array with malloc in C, but I get a segmentation fault calling the struct array.我正在创建一个指向结构指针的指针,以在 C 中使用 malloc 创建一个动态数组,但我得到一个调用结构数组的分段错误。 Here is a quick rundown of my code:这是我的代码的简要说明:

#include <stdio.h>

typedef struct {
    int test1;
    int test2;
    }testStruct;

int main() {
    testStruct **neato;

    neato = (testStruct **) malloc( sizeof(testStruct *) * 5);
    // Array of 5 for convience

    // any neato[x]->testy call results in segmentation fault.
    scanf("%d", &neato[0]->test1);    // Segmentation fault

    return 0;
    }

I tried other calls like (*neato)[0].test1 and all result in segmentation fault.我尝试了 (*neato)[0].test1 等其他调用,但都导致分段错误。 This is obviously not the proper way to do this or my GNU compiler is seriously outdated.这显然不是执行此操作的正确方法,或者我的 GNU 编译器已经严重过时了。

You've allocated enough memory for 5 pointers.您已经为 5 个指针分配了足够的 memory。 You have not however initialized the pointers, so they are garbage.但是你还没有初始化指针,所以它们是垃圾。 Allocate the pointers and then proceed to initialize each pointer.分配指针,然后继续初始化每个指针。

int elems = 5;

neato = malloc(sizeof(testStruct *) * elems);
for( i = 0; i < elems; ++i ) {
    neato[i] = malloc(sizeof(testStruct));
}

On a side note, I don't see a need for an array of pointers here.附带说明一下,我认为这里不需要指针数组。 Why not simply allocate enough space for 5 testStruct s (ie, neato becomes a testStruct* ) and pass the address of that pointer to the function that initializes it?为什么不简单地为 5 个testStruct分配足够的空间(即, neato变成一个testStruct* )并将该指针的地址传递给初始化它的 function?

you aren't mallocing space for all the structures themselves you have to add您没有为必须添加的所有结构本身mallocing空间

for(int i = 0; i < 5; i++) {
    neato[i] = malloc(sizeof(testStruct));
}

After you malloc neato.在你 malloc neato 之后。 Also you should check your return value from malloc for NULL to make sure malloc passed.您还应该检查 malloc 的返回值是否为NULL ,以确保 malloc 通过。

You allocated array of pointers, but did not assign valid address to these pointers.您分配了指针数组,但没有为这些指针分配有效地址。

If you only want to create dynamic array, use just pointer to the struct:如果只想创建动态数组,只需使用指向结构的指针:

testStruct *neato;
neato = malloc( sizeof(testStruct) * 5);
scanf("%d", &neato[0].test1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM