简体   繁体   English

在结构内部创建指向结构的指针数组

[英]Creating array of pointers to struct inside a struct

Basiclly, I have a struct defined this way: 基本上,我有一个这样定义的结构:

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

Now, after creating the struct; 现在,在创建结构之后;

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

I have a problem creating the students list inside this struct. 我在此结构内创建学生列表时遇到问题。 I need the list to be an array of pointers, since I should make some kind of ADT program, I've tried to make it something like this: 我需要该列表是一个指针数组,因为我应该制作某种ADT程序,所以我试图使它像这样:

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

It doesn't matter how I tried to change it, I'm getting the same error: incompatible types when assigning to type 'struct Student' from type 'struct Student *'| 不管如何尝试更改它,我都会遇到相同的错误:从“结构学生*”类型分配给“结构学生”类型时,类型不兼容|

I've trying to create an array that I will be able to do something like; 我试图创建一个数组,我将能够做类似的事情;

T_Array->List[1]=Student_Pointer;

Thanks! 谢谢!

Change the type of the array to struct Student** that will be array of pointers : 将数组的类型更改为struct Student **,它将是指针数组:

struct student * --> a pointer to student. struct student *->指向学生的指针。 struct student ** --> a pointer to a pointer to student (what you need). struct student **->指向学生的指针(您需要)。

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

and the allocation: 和分配:

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

and then: 接着:

T_Array->List[1]=Student_Pointer;

struct Student* List; List is a pointer of Student When you do List[10] what youre doing is basicaly *(List+10) that means get Student from the 11th position List是学生的指针当您执行List [10]时,您所做的基本上是*(List+10) ,这意味着从第11位获得学生

If you want an array of pointers you need to do something like 如果您想要一个指针数组,则需要执行以下操作

struct Student **List;
and then 接着
List = (Student **)malloc(10*sizeof(Student **))
List would then have memory allocated for 10 pointers of student wich would be size of int for each in the end 列表将为10个学生指针分配内存,最后每个指针的大小为int

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

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