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

Change characters in a string array in C

我尝试将字符串数组中的 'a' 个字符更改为 'e'。但是我收到一条错误 *pos = 'e'; 行。它说 "Main.exe has stopped working"。我不明白这个问题。你有什么想法吗?

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

你的不是字符串数组,它是指向字符串文字的指针数组,你不能更改字符串文字。

要使其成为数组,试试这个

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

您可能需要将 space 分配给 malloc(),然后使用 strcpy() 复制文字,然后该副本将是可修改的。