如果 char*s 是只读的,为什么我可以覆盖它们? [英] If char*s are read only, why can I overwrite them?
问题描述
我的课程告诉我 char*s 是静态的/只读的,所以我认为这意味着你在定义它们后无法编辑它们.但是当我跑步时:
My course taught me that char*s are static/read only so I thought that would mean you can't edit them after you have defined them. But when I run:
char* fruit = "banana";
printf("fruit is %s\n", fruit);
fruit = "apple";
printf("fruit is %s\n", fruit);
然后它编译得很好并给了我:
Then it compiles fine and gives me:
fruit is banana
fruit is apple
为什么?我是否误解了只读意味着什么?对不起,如果这很明显,但我是编码新手,我无法在网上找到答案.
Why? Have I misunderstood what it means to be read-only? Sorry if this is obvious but I'm new to coding and I can't find the answer online.
推荐答案
呈现的代码片段不会更改字符串文字本身.它只改变存储在指针 fruit
中的值.
The presented code snippet does not change the string literals themselves. It only changes the values stored in the pointer fruit
.
你可以想象这些线条
char* fruit = "banana";
fruit = "apple";
以下方式
char unnamed_static_array_banana[] = { 'b', 'a', 'n', 'a', 'n', 'a', '\0' };
char *fruit = &unnamed_static_array_banana[0];
char unnamed_static_array_apple[] = { 'a', 'p', 'p', 'l', 'e', '\0' };
fruit = &unnamed_static_array_apple[0];
这些语句不会更改与字符串文字对应的数组.
These statements do not change the arrays that correspond to the string literals.
另一方面,如果你会尝试写作
On the other hand if you will try to write
char* fruit = "banana";
printf("fruit is %s\n", fruit);
fruit[0] = 'h';
^^^^^^^^^^^^^^
printf("fruit is %s\n", fruit);
也就是说,如果您尝试使用指向它的指针(指向字符串文字的第一个字符)来更改字符串文字,那么程序将具有未定义的行为.
that is if you will try to change a string literal using a pointer that points to it (to the first character of the string literal) then the program will have undefined behavior.
来自 C 标准(6.4.5 字符串文字)
From the C Standard (6.4.5 String literals)
7 未指定这些数组是否不同,只要它们元素具有适当的值.如果程序试图修改这样的数组,行为未定义.
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*s 是只读的,为什么我可以覆盖它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!