Ç字符指针问题 [英] c char pointer problem
问题描述
如果我们声明的char * p =你好;
则因为它是写在数据部分中,我们不能修改其中p指向的内容,但我们可以通过修改指针本身。但我发现在C陷阱与缺陷这个例子
安德鲁·柯尼希
AT& T公司贝尔实验室
美利山,新泽西州07974
if we declare char * p="hello";
then since it is written in data section we cannot modify the contents to which p points but we can modify the pointer itself. but i found this example in C Traps and Pitfalls
Andrew Koenig
AT&T Bell Laboratories
Murray Hill, New Jersey 07974
的例子是
char *p, *q;
p = "xyz";
q = p;
q[1] = ’Y’;
①将指向包含字符串XYZ存储器。所以将P,因为p和q指向相同的存储器
q would point to memory containing the string xYz. So would p, because p and q point to the same memory.
怎么是真的,如果我提到的第一条语句也是如此..
同样地,我跑到下面code
how is it true if the first statement i mentioned is also true.. similarly i ran the following code
main()
{
char *p="hai friends",*p1;
p1=p;
while(*p!='\0') ++*p++;
printf("%s %s",p,p1);
}
和得到的输出为兴业银行!gsjfoet
请解释我们如何在这两种情况下,都能够修改内容是什么?
在此先感谢
please explain how in both these cases we are able to modify contents? thanks in advance
推荐答案
您同样的例子使我的系统上分段错误。
Your same example causes a segmentation fault on my system.
您正在运行到未定义的行为在这里。 。数据
(注意,字符串可能会在的.text
太)不一定是一成不变的 - 难保机器将写保护内存(通过页表),根据不同的操作系统和编译器。
You're running into undefined behavior here. .data
(note that the string literal might be in .text
too) is not necessarily immutable - there is no guarantee that the machine will write protect that memory (via page tables), depending on the operating system and compiler.
这篇关于Ç字符指针问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!