关于C语言中字符指针的困惑 [英] Confusion about Character Pointers in C
问题描述
C语言中的字符指针使我感到困惑.
The character pointers in C is confusing me.
假设我们有一个char指针,它指向字符串 constant 的第一个字符.
Suppose we have a char pointer, which points to the first character of string constant.
char *a="ABCD";
然后我们不能使用指针a更改该字符的值,因为以下语句会导致分段错误.
Then we cannot change the value of that character using the pointer a, as following statement results in a segmentation fault.
*a='X';
现在假设我们有一个char指针,它指向一个字符 constant .
Now suppose we have a char pointer, which points to a character constant.
const char B='X';
char *ptr=&B;
然后我们可以使用语句更改该字符的值
Then we are allowed to change the value of that character using the statement
*ptr='Z';
我的问题是,这是未定义行为的情况,证明C不够健壮吗?还是涉及更深层次的逻辑?
My question is that is this a case of undefined behaviour proving C is not robust? Or is there some deeper logic involved?
推荐答案
指针的行为有所不同的原因是C程序具有多个内存段,其中一些是受保护的.
The reason the pointer behaves differently is that C program has several memory segments, some of which are protected.
然后我们不能使用指针a更改该字符的值,因为以下语句会导致分段错误.
Then we cannot change the value of that character using the pointer a, as following statement results in a segmentation fault.
与其他常量不同,字符串常量被放置在受保护的段中.尝试修改此段会导致未定义的行为(即您的程序可能会出现段错误).
Unlike other constants, string constants are placed into a protected segment. Any attempt to modify this segment results in undefined behavior (i.e. your program could segfault).
由于指针指向字符串常量,因此不能修改其指向的值.如果使用数组将常量的副本强制放入可修改的内存中,则将允许相同的修改:
Since your pointer points into a string constant, the value to which it points cannot be modified. If you force a copy of the constant into modifiable memory by using an array, the same modification would be allowed:
char a[]="ABCD";
*a='X';
然后我们就可以使用以下语句更改该[单个]字符的值
Then we are allowed to change the value of that [single] character using the statement
这是因为字符常量总是复制到可修改的内存中.
This is because character constant is always copied into modifiable memory.
这篇关于关于C语言中字符指针的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!