本文介绍了如果char * s是只读的,为什么我要覆盖它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的课程告诉我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 corresponds to the string literals.

另一方面,如果您尝试写

On the other hand if you tried to write

char* fruit = "banana";
printf("fruit is %s\n", fruit);
fruit[0] = 'h';
^^^^^^^^^^^^^^
printf("fruit is %s\n", fruit);

也就是说,如果您尝试使用指向它的指针(指向字符串文字的第一个字符)来更改字符串文字,那么程序将具有未定义的行为.

that is if you tried to change a string literal using a pointer that points to it (to the first character of the string literal) then the program had undefined behavior.

根据C标准(6.4.5字符串文字)

From the C Standard (6.4.5 String literals)

这篇关于如果char * s是只读的,为什么我要覆盖它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 02:34