2016-04-30 41 views
0

我需要爲結構中的元素分配字符串(字符大小[255])。該結構是這樣的:C使用函數將字符串值分配給結構中的字符串元素

struct node{ 
    int ID, YEAR, MONTH, DAY 
    char CATEGORY[255], DETAIL[255]; 
    double AMOUNT; 
    struct node * next; 
} 
struct node * head = NULL; 

,我有一些代碼從一個文本文件中獲取值,並將其設置爲可變的,我再傳給add_struct功能看起來像這樣:

void add_struct(int i, char c, char d, double a, int y, int m, int da){ 
    if (head == NULL){ 
     head = (struct node *) malloc(sizeof(struct node)); 
     head->ID = i; 
     head->CATEGORY = c; 
     head->DETAIL = d; 
     head->AMOUNT = a; 
     head->YEAR = y; 
     head->MONTH = m; 
     head->DAY = da; 
    } 

    else { 
     struct node * p = head; 
     while(p->next != NULL) p = p->next; 
     p->next = (struct node *) malloc(sizeof(struct node)); 
     p->next->ID = i; 
     p->next->CATEGORY = c; 
     p->next->DETAIL = d; 
     p->next->AMOUNT = a; 
     p->next->YEAR = y; 
     p->next->MONTH = m; 
     p->next->DAY = da; 
    } 
} 

我收到錯誤消息:

"incompatible types when assigning to type 'char[255]' from type 'char'" 

如何正確地將這些值分配給元素CATEGORY和DETAIL?

+0

'字符C' - >'的char * C' ...'P->下一步 - >類別= C; ' - >'strcpy(p-> next-> CATEGORY,c);' – BLUEPIXY

+0

'char c,char d'真的意味着單個字符還是指向char(字符串)的指針? – fluter

+0

還需要XXX'-> next = NULL;' – BLUEPIXY

回答

1

struct的CATEGORYDETAIL字段被定義爲255個字符陣列,而cdchar變量。所以,你應該功能更改爲void add_struct(int i, char *c, char *d, double a, int y, int m, int da)和字符串複製到分配結構:

strcpy(head->CATEGORY, c); 
strcpy(head->DETAIL, d); 
+0

值c和d不僅僅是字符,而是char數組大小255以及。一個例子就像CATEGORY是「餐廳」,細節是「華夫餅屋」。這是否仍然有效? – user276019

+0

@ user276019在這種情況下,您需要修復函數簽名,並在函數中使用'strcpy'。看我的帖子。 – fluter

相關問題