2014-01-15 190 views
0

我需要幫助下面的代碼。這段代碼有什麼問題?

typedef struct orders 
{ 
    int quantity; 
    char foodname[50]; 
} ORDER; 

ORDER *ptr; 

typedef struct Table 
{ 
    int tableno; 
    int priority; 
    ORDER *orders; 
    struct Table *next; 
} TABLE; 

TABLE *head, *s; 
int n = 0; 

int insert(int tablenum, int prio, char foodname[], int qty) 
{ 
    TABLE *newO, *temp, *temp2; 
    newO = (TABLE*)malloc(sizeof(TABLE)); 
    newO->tableno = tablenum; 
    newO->priority = prio; 
    strcpy(newO->orders->foodname, foodname); 
    newO->orders->quantity = qty; 
     //more code here... 
} 

在這個程序的主要功能,用戶將被要求什麼表號,優先數,他們要訂購的食物,他們要的食物的量的名字。

此代碼還有一個showlist函數,它將打印出列表中從最高優先級到最低優先級的所有數據。現在

我的問題是,比如我已經有兩個不同的事務,什麼情況是,我的第二個交易拷貝「foodname」我的第一個交易的「量」。

請幫幫我吧。

+0

「Table-> orders」是指向單個「Order」條目還是元素數組的指針?你的結構和標籤命名也不一致,這會導致混淆。 – Dai

回答

2
TABLE *newO = (TABLE*)malloc(sizeof(TABLE)); 

分配內存TABLE,而不是orders,此malloc調用後只是一個未初始化的指針所以這行:

newO->orders->quantity = qty; 

調用一個未定義的行爲。您需要分配訂單的內存爲好,例如:

TABLE *newO = (TABLE*)malloc(sizeof(TABLE)); 
newO->orders = (ORDER*)malloc(10*sizeof(ORDER)); 
... 
newO->orders[0]->quantity = qty; 

...雖然說實話,這是很難說orders是否真的意味着是一個數組。

+0

感謝您的回覆。 – user84275

+1

@haccks:他沒有權限允許他投票:) – LihO

+0

哎呀! :)。但他應該接受答案。 – haccks