[英]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*));
不管如何嘗試更改它,我都會遇到相同的錯誤:從“結構學生*”類型分配給“結構學生”類型時,類型不兼容|
我試圖創建一個數組,我將能夠做類似的事情;
T_Array->List[1]=Student_Pointer;
謝謝!
將數組的類型更改為struct 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是學生的指針當您執行List [10]時,您所做的基本上是*(List+10)
,這意味着從第11位獲得學生
如果您想要一個指針數組,則需要執行以下操作
struct Student **List;
接着
List = (Student **)malloc(10*sizeof(Student **))
列表將為10個學生指針分配內存,最后每個指針的大小為int
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.