这可能是因为调用代码没有为字符串分配足够的空间。它必须始终至少分配一个大于字符串中可见字符的空间,以允许\ 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