2016-10-11 13 views
-1

我想一個值分配給我的char *這樣的:分配值字符數組在C不工作

char *text; 
struct node *ptr = head; 

//start from the beginning 
while(ptr != NULL) 
{   
    text = ptr->key + ";" + ptr->data + ";\n"; 
    ptr = ptr->next; 
    fprinft(f, text); 
} 

鍵值是char[]和數據值的int

我得到以下錯誤:

Error: invalid operands to binary + (have ‘int’ and ‘char *’) text = ptr->key + ";" + ptr->data + ";\n";

有誰知道如何解決這個問題?

+0

'strcat'是你的朋友。 –

+1

你的編譯器肯定會告訴你一些關於這段代碼的有用信息。 – EOF

+0

錯誤:無效的操作數爲二進制+(有'char *'和'char *') text = ptr-> key +「;」 + ptr-> data +「; \ n」; – mafioso

回答

2

由於ptr->key串聯,";"ptr->data";\n"不需要AFTE存在循環,只是打印到文件。 @user3386109

// Not needed 
// char *text; 

struct node *ptr = head; 

while(ptr != NULL) { 
    //   v--v----- printf specifiers for a pointer to a string and int 
    fprinft(f, "%s;%d;\n", ptr->key, ptr->data); 
    ptr = ptr->next; 
} 
-2

首先,你需要爲你的*text分配內存,然後用strcat的功能添加這些字符串連接在一起......

#include <string.h> 
void function(...) { 
    char* text = (char*)malloc(sizeof(char) * 100); // for 99 chars + NULL 
    text[0] == 0; 
    struct node* ptr = head; 

    //start from the beginning 
    while(ptr != NULL) 
    { 
    if(text[0] == 0) //you cant strcat empty string, only existing one 
     strcpy(text, ptr->key); 
    else 
     strcat(text, ptr->key); 
    strcat(text, ";"); 
    strcat(text, ptr->data); 
    strcat(text, ";\n"); 
    ptr = ptr->next; 
    fprinft(f, text); 
    } 
} 

此代碼假定兩者ptr->keyptr->data是字符數組(串),如果他們都沒有,你需要將它們轉換爲字符串:看看itoa功能...

+0

'atoi'將字符串轉換爲int ..... – mafioso

+0

當然,我在考慮'itoa'。小混亂。 – Rorschach

+1

你從哪裏得到「你不能strcat空串,只有現有的」? – EOF

-1

你需要malloc()它。這是因爲在C字符串存儲在內存中的字符數組,但如果你不這樣做的malloc(),並初始化字符串作爲

char* string = "this is a string"; 

它會被存儲在只讀存儲器中。

你可以做的是malloc()它或將它作爲一個數組存儲。

希望這會有所幫助!