在结构中创建指向结构的指针数组

Creating array of pointers to struct inside a struct

基本上,我有一个这样定义的结构:

struct D_Array
{
    int Capacity;
    int Cur_Size;
    struct Student* List;
};

现在,在创建结构之后;

struct D_Array* T_Array;
if (T_Array = malloc(sizeof(struct D_Array)) == NULL)
{
    printf("There has been a problem with memory allocation. Exiting the program.");
    exit (21);
}

我在此结构中创建学生列表时遇到问题。我需要列表是一个指针数组,因为我应该制作某种 ADT 程序,所以我尝试将其制作成这样:

T_Array->Capacity = 10;
T_Array->Cur_Size = 0;
T_Array->List[10]= (struct Student*) malloc(sizeof (struct Student*));

无论我如何尝试更改它,我都会遇到同样的错误: 从类型 'struct Student *'|

分配给类型 'struct Student' 时类型不兼容

我正在尝试创建一个数组,我将能够执行类似的操作;

T_Array->List[1]=Student_Pointer;

谢谢!

将数组类型更改为 Student** 结构,这将是指针数组:

struct student * --> 指向学生的指针。 struct student ** --> 指向学生指针的指针(你需要的)。

struct D_Array
{
    int Capacity;
    int Cur_Size;
    struct Student** List;
}

和分配:

T_Array->List = malloc (sizeof (struct Student*) *  lengthofarray);

然后:

T_Array->List[1]=Student_Pointer;

struct Student* List; List 是 Student 的指针 当您执行 List[10] 时,您所做的基本上是 *(List+10) 表示从第 11 位开始获取 Student

如果你想要一个指针数组,你需要做类似

的事情

struct Student **List;
然后
List = (Student **)malloc(10*sizeof(Student **))
然后 List 将为 student 的 10 个指针分配内存,最后每个指针的大小为 int