在 C 中重新初始化 const char 数组不会出错

Re-Initializing a const char array in C is not giving error

在初始化 const char 数组时,我尝试更改字符串并且能够毫无问题地进行更改。

我正在学习如何初始化 const char 数组。 我想我在这里犯了一些我找不到的错误。

int main(int argc, char const *argv[])
{

    const char *strs[10];
    strs[0] = "wwww.google.com";
    printf("%s\n", strs[0]);
    strs[1] = "https://wwww.google.com";
    strs[0] = "ss";
    printf("%s\n", strs[0]);
    return 0;
}

输出:

1st init: wwww.google.com
2nd init: ss -> Here, I expect it to throw error

const char* s = "Hi";

告诉编译器指针指向的 content 是常量。这意味着 s[0] = 'P'; 将导致编译错误。但是你可以修改指针。另一方面,

char* const s = "Hi";

告诉编译器指针是常量。这意味着 s = "Pi"; 将导致编译错误。但是当你尝试修改字符串*

时不会抛出编译错误

您的代码描述了前者的行为,而不是您认为的后者


* 修改字符串文字将调用未定义的行为

用简单的英语来说(不一定 100% 准确,但可以概念化),这个

const char *strs[10];

初始化一个包含 none 个常量元素的常量数组 strs。因此,数组中的元素可以改变,但数组本身不能改变

const char *strs[10];

strs 是一个包含 10 个指向 const char 的指针的数组。您可以更改指针;你不能改变字符

strs[2] = NULL; // ok: change the pointer
strs[0][0] = '#'; // wrong; cannot change the char

也许试试

const char * const strs[10] = {"www.google.com",
                               "https://www.google.com",
                               "www.google.com/",
                               "https://www.google.com/",
                               NULL, NULL };

这使得 strs 成为一个包含 10 个 read-only 指针的数组 const char。初始化后不能更改指针。