在C中更改字符串数组中的字符

Eng*_*gin 0 c arrays string pointers character

我尝试在字符串数组中将'a'字符更改为'e'.但我收到一个错误*pos = 'e'; 行.它说"Main.exe已停止工作".我无法理解这个问题.你有什么主意吗?

int main(void) {
    char *sehirler[] = { "Istanbul", "Ankara", "Izmir", "\0" };
    int i;
    for (i = 0; *sehirler[i] != '\0'; ++i) {
        char *pos = sehirler[i];
        while (*pos != '\0') {
            if (*pos == 'a') {
                printf("%c", *pos);
                *pos = 'e';          //ERRROR
            }
            pos++;
        }
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Iha*_*imi 5

你的不是一个字符串数组,它是一个指向字符串文字的指针数组,你不能改变字符串文字.

要使它成为一个数组,试试这个

int main(int argc, char *argb[])
{
    char sehirler[4][9] = {"Istanbul", "Ankara", "Izmir", ""};
    /*            ^  ^
     *            |  |__ Number of characters in `Istanbul' + '\0'
     *            |_ Number of strings in the array
     */
    int   i;
    for (i = 0 ; *sehirler[i] != '\0' ; ++i)
    {
        char *pos = sehirler[i];
        while (*pos != '\0')
        {
            if (*pos == 'a')
            {
                printf("%c", *pos);
                *pos = 'e';          //ERRROR
            }
            pos++;
        }
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

您可能需要分配空间,malloc()然后使用它strcpy()来制作文字的副本,然后副本将是可修改的.