2013-10-15 202 views
0

這是我的結構和方法,但它不起作用。任何人都可以幫我解決問題嗎?感謝將元素添加到鏈接列表?

這是結構:

struct album 
{ 
    char singerName[30]; 
    char year[4]; 
    char title[30]; 

    char songName[50]; 
    char songLength[50]; 
    struct album *next; 
}; 
struct album *a=NULL; 

這是方法:

struct album *addAlbum(struct album *list,char* year,char *title,char *singerName) 
{ 
    struct album *temp; 
    temp =(struct album*) malloc(sizeof(struct album)); 
    strcpy(temp->singerName,singerName); 
    strcpy(temp->title,title); 
    strcpy(temp->year,year); 
    temp -> next = NULL; 

    if(list==NULL) 
    { 
     return temp; 
    } 
    else 
    { 
    temp->next=list; 
     return temp; 
    } 
} 
+0

作業時間(再次)。請提供編譯和演示問題的代碼 –

+0

如果您自己無法完成作業,您是否至少可以指出編譯器如何說明問題的性質和位置? –

+0

歡迎來到Stack Overflow。請儘快填寫[關於]頁面。你一年只分配了4個字符;這應該是5以允許4位數年份。可以說,你應該對你分配的結構成員進行長度檢查。你可以通過使用'temp-> next = list;'來簡化代碼,如果沒有條件(如果list是NULL,它將是正確的,如果不是則它將是正確的),那麼'return temp;'。什麼方式不起作用?調用這個函數的代碼是什麼樣的? –

回答

1

上目的地緩衝不足控制。

如果輸入year爲「2013」​​,則以下可能會失敗。這是一個字符串,需要4 + 1個字節。

char year[4];  
... 
strcpy(temp->year,year); 

簡單的修復方法是使用char year[5]。但是,這可以在路上開啓。

更好地使用strncpy(temp->year,year, sizeof(temp->year)-1); temp->year[sizeof(temp->year)-1] = '\0'。存在其他選項來防止溢出。