我試圖創建一個ADT, 首先,這裏是關於它的基本信息:C-的ADT是不斷崩潰
typedef struct orange_t* Orange;
typedef enum {
JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC,
} Month;
struct orange_t {
short size;
Month expirationMonth;
char** foodCompanies;
int maxNumberOfFoodCompanies;
int sellingPrice;
};
現在我試着去創建一個將「創建一個函數「新橙這樣的:
Orange orangeCreate(short size,Month expirationMonth
,int maxNumberOfFoodCompanies,int sellingPrice)
{
Orange new_orange=(Orange)malloc(sizeof(struct orange_t));
if(new_orange==NULL)
{
return NULL;
}
if((sellingPrice<0)||(size>256||size<1)||(maxNumberOfFoodCompanies<0)||(expirationMonth>12)
||(expirationMonth<1))
{
return NULL;
}
new_orange->sellingPrice=sellingPrice;
new_orange->maxNumberOfFoodCompanies=maxNumberOfFoodCompanies;
new_orange->expirationMonth=expirationMonth;
new_orange->size=size;
for(int i=0;i<new_orange->maxNumberOfFoodCompanies;i++)
{
new_orange->foodCompanies[i]=NULL;
}
return new_orange;
}
當我試圖檢查與簡單main()
功能:
int main()
{
Orange orange=orangeCreate(3,JAN,10,4);
printf("the size is %d\n",orange->size);
orangeDestroy(orange);
return 0;
}
該程序不斷崩潰,我想我沒有更改橙色的值,因爲我應該,他們可能仍然是NULL
。 我在哪裏出錯了?
您還沒有分配'foodCompanies'任何地方,但試圖索引並將其分配。在C中爲 –
,'malloc()'和函數系列的返回值爲'void *'類型,可以將其分配給任何其他指針。鑄造返回類型是完全不必要的,並且在調試和維護代碼時會導致困難。 typedef名稱「Orange」具有誤導性,因爲它實際上是一種指針類型。對於typedef來說,更好的方法就是不帶指針的'struct orange_t',然後根據需要在代碼體中添加'*'。 – user3629249
枚舉以0開頭(除非另有特別定義),所以'expirationMonth'的檢查是不正確的,除非枚舉被修改,所以第一個條目是:'JAN = 1,' – user3629249