C 代码未按预期运行 - C 字符串 - 删除逗号

C code not Behaving as Expected - C Strings - Removing Commas

我很困惑以下代码没有按预期运行。

根据字符串的初始定义方式(即 char str[] = "1,000" 与 char *str = "1,000"),代码的行为有所不同。

代码如下:

#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 %s\n", str);
    printf("str is %s\n\n", removeCommasInString(str));
    
    printf("str2 is %s\n", str2);
    printf("str2 is %s\n\n", removeCommasInString(str2));
    
    printf("str3 is %s\n", str3);
    printf("str3 is %s\n", 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 '[=10=]' 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() 函数永远不会到达“puts”语句。 而且我从来没有看到错误消息。

我确定我缺少的是简单的东西。

char* str3 = "1,000";

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

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