Defining an array of structures in C?

前端 未结 3 795
温柔的废话
温柔的废话 2021-01-22 17:51

main.h

#define  DATA  struct   data
DATA
{
  int id;
  char data;
}

main.c

DATA *listOfData[100];

So at this

3条回答
  •  心在旅途
    2021-01-22 18:47

    This is because you have defined an array of pointers. But you never initialized any of the pointers.

    Therefore:

    printf(listOfData[5]->data);
    

    will crash (undefined behavior) because you are dereferencing the (invalid) pointer at index 5.

    *(And that's a very odd way to define a struct...)

    To fix this issue, you will need to allocate for each of the pointers in the array. If you don't actually need it to be an array of pointers, then it might be better to just make it array of the struct itself:

    DATA listOfData[100];
    

    and access it as:

    listOfData[5].data
    

    Then you don't have to deal with allocating each element.

提交回复
热议问题