2017-04-18 71 views
0

我是C語言的新手。我需要連接char數組和char。在Java中,我們可以使用'+'操作,但在C中是不允許的。 Strcat和strcpy也不適合我。我怎樣才能做到這一點?我的代碼如下連接字符數組和char

void myFunc(char prefix[], struct Tree *root) { 
    char tempPrefix[30]; 
    strcpy(tempPrefix, prefix); 
    char label = root->label; 
    //I want to concat tempPrefix and label 

我的問題從concatenate char array in C因爲它Concat的字符數組與另一個不同,但礦是一個字符數組使用char

+2

C [concatenate char array可能重複](http://stackoverflow.com/questions/2218290/concatenate-char-array-in-c) –

+1

增加了一個解釋我的是如何不同於以前的問題 –

+0

歡迎到堆棧溢出!請說明迄今爲止的研究/調試工作。請先閱讀[問]頁面。 –

回答

1

而是很簡單。主要關心的是tempPrefix應該有足夠的空間用於前綴+原始字符。由於C字符串必須以空字符結尾,因此您的函數不應複製超過28個字符的前綴。它是30(緩衝區大小)-1(根標籤字符)-1(終止空字符)。幸運的是標準庫有strncpy

size_t const buffer_size = sizeof tempPrefix; // Only because tempPrefix is declared an array of characters in scope. 
strncpy(tempPrefix, prefix, buffer_size - 3); 
tempPrefix[buffer_size - 2] = root->label; 
tempPrefix[buffer_size - 1] = '\0'; 

這也是值得的不是硬編碼在函數調用的緩衝區大小,從而使您可以增加其大小以最小的變化。


如果你的緩衝區不是一個確切的配合,需要一些更多的legwork。該方法與以前幾乎完全相同,但需要致電strchr才能完成圖片。

size_t const buffer_size = sizeof tempPrefix; // Only because tempPrefix is declared an array of characters in scope. 
strncpy(tempPrefix, prefix, buffer_size - 3); 
tempPrefix[buffer_size - 2] = tempPrefix[buffer_size - 1] = '\0'; 
*strchr(tempPrefix, '\0') = root->label; 

我們再次複製不超過28個字符。但是顯式地用NUL字節填充結尾。現在,由於strncpy在NUL字節填充到count的緩衝區中,以防被複制的字符串更短,實際上覆制前綴後的所有內容現在爲\0。這就是爲什麼我馬上尊重strchr的結果,保證指出一個有效的字符。第一個可用空間是確切的。

+0

我沒有得到預期的輸出。我可以看到附加字符在我的tempPrefix字符數組的第28個位置,但是當我打印它時,它不在那裏。我們不應該將數組連接到數組中當前文本的下一個位置,而應該連接到數組的末尾。 –

+0

@GeorgeKlimas - 我的小錯誤。 'strncpy'副本*最多*個數字符,包括。這意味着對它的呼叫需要進行調整。查看我的編輯細節。 – StoryTeller

+0

我仍然沒有在char數組中追加字符。調試顯示角色正被追加到28位置。 –

0

strXXX()系列函數大多操作(除搜索相關的),所以你將無法直接使用庫函數。

您可以找到現有空終止符的位置,將其替換爲要連接的char值並在其後添加空終止符。但是,您需要確保您有足夠的空間讓源保留級聯的字符串

像這樣(未測試)

#define SIZ 30 


//function 
char tempPrefix[SIZ] = {0};  //initialize 
strcpy(tempPrefix, prefix); //copy the string 
char label = root->label;  //take the char value 

if (strlen(tempPrefix) < (SIZ -1)) //Check: Do we have room left? 
{ 
    int res = strchr(tempPrefix, '\0'); // find the current null 
    tempPrefix[res] = label;    //replace with the value 
    tempPrefix[res + 1] = '\0';   //add a null to next index 
} 
+0

我沒有在這裏得到輸出。我可以看到'res'正在變成負值。這是問題嗎? –