为什么我得到 "Access violation" 写入位置?

why am I getting "Access violation" writing location?

我正在尝试使用 strtok 来获取带有 [=13=] 的字符串,而不是使用空格来将 [=13=] 替换为 #,所以我使用 strtok 为了那个原因。但我得到了 - 访问冲突写入位置 在这一行 - char* word = strtok(stringOfNumberSign, delimiters);

char* addNumberSignToString(char* stringOfNumberSign)
{
    int numOfWords = 0;
    char* delimiters = " ";
    char* word = strtok(stringOfNumberSign, delimiters);
    while (word)
    {   
        numOfWords++;
        word = strtok(NULL, delimiters);
    }

    return stringOfNumberSign;
}

int main()

{
    char* stringForNumberSign = "welcome to hello world";
    char* result;
    result = addNumberSignToString(stringForNumberSign);
    printf("%s", result);
}

函数 strtok 更改传递的字符串。

来自C标准(7.23.5.8的strtok函数)

4 The strtok function then searches from there for a character that is contained in the current separator string. If no such character is found, the current token extends to the end of the string pointed to by s1, and subsequent searches for a token will return a null pointer. If such a character is found, it is overwritten by a null character, which terminates the current token. The strtok function saves a pointer to the following character, from which the next search for a token will start.

但是您不能更改字符串文字。任何更改字符串文字的尝试都会导致未定义的行为。

来自 C 标准(6.4.5 字符串文字)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

而您正在尝试更改字符串文字

char* stringForNumberSign = "welcome to hello world";
//...
result = addNumberSignToString(stringForNumberSign);

至少你应该使用字符数组而不是字符串文字

char stringForNumberSign[] = "welcome to hello world";

注意你的函数没有意义。