2017-03-28 139 views
0

我有一個函數可以完成一些字符串的操作,但它必須通過將原始字符串複製到char數組中來保存原始字符串,並將其全部替換爲大寫字母任何W/W爲五printf(「%s」)返回奇怪值

char* function(const char* text){ 

    int textLength = strlen(text); 
    char text_copy[textLength]; 

    for(int i = 0; i < textLength; i++){ 
    if(text[i] == 'W' || text[i] == 'w') 
     text_copy[i] = 'V'; 
    else 
     text_copy[i] = toupper(text[i]); 
    } 

    return 'a'; 
} 

它並不真正的問題是什麼函數返回,但每當我試圖printf("%s\n", text_copy);,一些字符串,它返回:

belfast: BELFAST 
please: PLEASE 
aardvark: AARDVARK?? 
hello world: HELLO VORLD 
taxxxiii: TAXXXIII??? 
swag: SVAG? 

爲什麼有些琴絃變得很好,有些琴絃不會?謝謝。

+6

'text_copy'具有本地作用域,它不是'null-terminated',並且沒有空終止符.... ..... – LPs

+0

問號是否出現在輸出中,或者它們是否打算標記以非預期方式處理的字符串? – Codor

+0

@LPs將'text_copy'設置爲'textLength + 1',然後'text_copy [textLength] ='\ 0';'似乎已經解決了這個問題。謝謝! – Holsen

回答

3

你需要用空字符結束的副本。

char text_copy[textLength+1]; 
... 
text_copy[textLength]='\0'; 

雖然如果你從你的函數返回它(不明確),你應該改用它來代替它。

+0

工作,謝謝。它不應該從函數返回,但感謝您的高舉! – Holsen

1

爲什麼一些字符串變好而有些不變呢?

純粹的機會。

您只爲字符串中的可見字符分配enoufgh空間,而不是終止\0。你只是幸運的是,對於某些字符串來說,一個空字節在字符數組後面的堆棧中。

更改您的代碼是這樣的...

int textLength = strlen(text); 
char text_copy[textLength + 1]; // << enough space for the strings and \0 

for(int i = 0; i < textLength; i++){ 
    if(text[i] == 'W' || text[i] == 'w') 
    text_copy[i] = 'V'; 
    else 
    text_copy[i] = toupper(text[i]); 
} 
text_copy[textLength] = '\0'; // Make sure it is terminated properly. 
+0

'text_copy'有自動存儲和函數返回'char *'.... – LPs