[英]How to set all values to NULL struct array within a struct array in C
基本上,我有兩個結構,我想制作一個A結構數組,在每個A結構中,我想要一個包含50個B結構的數組。 因此,我假設我們將使用雙指針。
struct A{
char* a_word;
struct B** b_list;
};
struct B{
char* b_word;
int b_value;
};
當調用初始化函數時,我會像這樣初始化結構。 我的目標是在分配內存時將所有值設置為NULL。
struct Word** initialize()
{
int k;
int i;
struct A** A_list = calloc(BUFFSIZE, sizeof(struct A*));
for(k =0; k < BUFFSIZE; k++)
{
A_list[k] = calloc (1, sizeof(struct A));
A_list[k]-> b_list = calloc(50, sizeof(struct B*));
for(i = 0; i < 50; i++)
{
A_list[k]->b_list[i] = calloc(1, sizeof(struct B));
}
}
return hashTable;
}
初始化所有這些值后,我就能做到。 。 。
if(A[43]->a_word == NULL) //43 unallocated value
{
printf("This is null\n");
//program prints this statement - good
//program knows that this value is NULL
}
但是我也想要。 。
if(A_list[44]->b_list[0] == NULL)
{
printf("This is also null");
//This should be printed but nothing happens
}
出於某種原因,無論是否將上述if語句設置為== NULL
或!= NULL
,程序都不會從該if語句中輸出任何內容。 內存中發生了什么,如何正確分配所有內容,因此該值默認設置為NULL,因此我可以輸入一個值?
編輯:也每當嘗試做A_list[value1]->b_list[value2] = strdup("string");
我遇到了細分錯誤,這很可能源於相同的問題。
正如WhozCraig在對該問題的評論中已經提到的,此代碼
for(i = 0; i < 50; i++)
{
A_list[k]->b_list[i] = calloc(1, sizeof(struct B));
初始化b_list
的前50個元素以指向有效內存,即非0
, b_list
是calloc()
永不失敗。 樂觀地說,您最好測試那些元素是否為!= NULL
。
...如果我將上述if語句設置為== NULL或!= NULL,則程序絕對不會輸出任何內容
該代碼似乎不在此處刷新stdout
:
if(A_list[44]->b_list[0] == NULL)
{
printf("This is also null");
通過添加最終\\n
更改此設置:
if(A_list[44]->b_list[0] != NULL)
{
printf("This isn't null\n");
由於默認情況下stdout
是行緩沖的,因此如果檢測到換行,則將刷新所有內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.