這可能是因爲調用代碼沒有爲字符串分配足夠的空間。它必須始終至少分配一個大於字符串中可見字符的空間,以允許\ 0的空間。
這就是說,由於字符串是可變的,所以不需要返回字符串。它會在你工作時修改字符串。
這裏將是你的代碼的工作版本:
void detab(char * myStr)
{
for (int i = 0; myStr[i] != '\0'; i++)
if (myStr[i] == '\t')
myStr[i] = ' ';
}
char theString[] = "\thello\thello\t";
printf("Before: %s", theString);
detab(theString);
printf("After: %s", theString);
另外,請記住以下幾點:
char buffer[4] = "test"; //THIS IS NOT SAFE. It might work, but it will overwrite stuff it shouldn't
char buffer[5] = "test"; //This is Ok, but could be an issue if you change the length of the string being assigned.
char buffer[] = "test"; //This is preferred for string literals because if you change the size of the literal, it will automatically fit.
UPDATE:此基礎上添加的主要方法,這裏是你的問題:
您需要更改
char * string = "\thello\thello";
要
char string[] = "\thello\thello";
的原因是,當你定義一個字符串,並將其分配給一個char *,它駐留在記憶的文字部分,並且不能安全地修改。相反,您應該將字符串文字分配給一個char [](它可以作爲char *傳遞,因爲這是它的實際類型)。這個語法將讓編譯器知道它應該在堆棧上分配空間,並用字符串文本中的值填充它,從而允許修改它。
char * joe =「blah」只是創建char *指針,並將其指向文本部分中的數據(它是不可變的)。
char joe [] =「blah」告訴編譯器在堆棧上創建一個長度合適的數組,用字符串文字加載它來創建char *指針,然後將指針指向啓動堆棧上的數據陣列。
你不能修改字符串在C字面[是否有可能修改的char在C語言的字符串?](https://stackoverflow.com/questions/1011455/is-it-it-it-of-char-in-c/1011545#1011545) – Rabbid76
我們不知道這個函數是否在字符串文字上被調用。你能否說明你是如何稱呼這個函數的,以及你如何聲明你作爲參數傳遞的東西? – e0k
@ e0k他說:但是當我在「\ thello \ thello \ t」上運行它時 – Rabbid76