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

标签 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;
}

最佳答案

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

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

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;
}

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

关于在 C 中更改字符串数组中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29501993/

相关文章:

java - Java中的对象数组的混洗: Why does this method work for int but not for my objects?

javascript - 在字符串前加零

c++ - 当进程结束时,处于 Sleep() 中间的线程会发生什么?

c++ - 适用于 Windows 7 的简单 "javac"样式命令行 C/C++ 编译器

javascript - 使用 JavaScript 从网格数组中删除列

java - 数组在 for 循环中初始化后丢失值/返回 null

Java - 用反斜杠 (\) 分割字符串

java - 如何使用流将二维 int 数组转换为单个字符串?

c - fork 和 usleep 错误

c - 找到一个子数组的最小值,而该值可能只有 1 或 2 或 3