C代码不符合预期- C字符串-删除逗号



我很困惑,下面的代码没有按照预期的方式运行。

根据字符串的初始定义(即char str[] = " 1000 "),代码的行为不同。Vs char *str = " 1000 ").

代码如下:

#include <stdio.h>
char* removeCommasInString (char *str);
int main()
{
char str[] = "1,000,000";
char str2[] = "10,000";
char* str3 = "1,000";

printf("str is %sn", str);
printf("str is %snn", removeCommasInString(str));

printf("str2 is %sn", str2);
printf("str2 is %snn", removeCommasInString(str2));

printf("str3 is %sn", str3);
printf("str3 is %sn", removeCommasInString(str3));

puts("Program has ended");
return 0;
}
char* removeCommasInString (char *str)
{
const char *r = str;    // r is the read pointer
char *w = str;          // w is the write pointer

do {
if (*r != ',')   

{
*w++ = *r;   // Set *w (a single character in the string) to *r
}
} while (*r++);      // At end of the string, *r++ will be '' or 0 or false
// Then loop will end
// The str string will now have all the commas removed!!
// The str pointer still points to the beginning of the
// string.

return str;
}

下面是我得到的输出:

str is 1,000,000
str is 1000000
str2 is 10,000
str2 is 10000
str3 is 1,000

...Program finished with exit code 0
Press ENTER to exit console.

逗号在str3中没有被删除。并且main()函数永远不会到达"put "声明。而且我从来没有看到错误信息。

我肯定我错过了一些简单的东西。

char* str3 = "1,000";

基本相同
char* str3 = (char*)"1,000";

,因为它指向字符串字面值(const char*),而其他的在运行时分配内存,所以它们是可修改的。字符串字面值不存储在堆栈或堆中,而是存储在只读内存中,因此不能修改。

最新更新