万一改变指针中的一个的值,其中,两个指针adrress相同 [英] changing the value of one of the pointer in case where, adrress of two pointers are same

查看:150
本文介绍了万一改变指针中的一个的值,其中,两个指针adrress相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我看到两个指针的地址是相同的问题在这里(两个指针的地址相同),也被蓝月亮回答。
这使我一些疑虑。由于两个指针都具有相同的地址我想改变指针中的一个的值,期望的值将在其他指针被改变过(因为它们具有相同的地址)。但它给分段错误。我显示它低于code。

 #包括LT&;&stdio.h中GT;
#包括LT&;&string.h中GT;诠释的main()
{
    的char * p =ABC;
    字符* P1 =ABC;
    的printf(%d个\\ n%d个\\ N(无效*)P,(无效*)P1);
    的printf(%S \\ n%S \\ n,P,P1);
    * P ='B';
    的printf(%d个\\ n%d个\\ N,P,P1);
    的printf(%S \\ n%S \\ n,P,P1);
}


解决方案

  

C90,6.1.4


  
  

如果该程序试图修改字符串文字两种形式中,
  行为是不确定的。


在您的情况下,这个不确定的行为是对你有利,让你在使用%d个是不是一个很好的做法,你应该得到赛格fault.Other比这个打印指针使用%p

现在从蓝月亮你给出答案的链接

你应该总是把 P P1 作为两个不同的指针(即使它们具有相同的内容),因为它们可能会或可能没有指向相同的地址。你不应该依赖于编译器优化。

I have a problem,I saw that the address of two pointers are same as in question here(Addresses of two pointers are same), also answered by blue moon. Which lead me to some more doubts. Since both the pointers have same address I thought to change the value of one of the pointers, expecting value will be changed in other pointer too(since they have same address). But its giving segmentation fault. I am showing it in a code below.

#include<stdio.h>
#include<string.h>

int main()
{
    char * p = "abc";
    char * p1 = "abc";
    printf("%d\n %d\n", (void *)p, (void *)p1);
    printf("%s\n %s\n", p, p1);
    *p = 'b';
    printf("%d\n %d\n", p, p1);
    printf("%s\n %s\n", p, p1);
}

解决方案

C90, 6.1.4

If the program attempts to modify a string literal of either form, the behaviour is undefined.

In your case this Undefined behaviour is in your favour so that you are getting Seg fault.Other than this printing pointer using %d is not a good practice, You should use %p.

Now from your given Link Answer of Blue Moon

you should always treat p and p1 as two different pointers (even though they have the same content) as they may or may not point to the same address. You shouldn't rely on compiler optimizations.

这篇关于万一改变指针中的一个的值,其中,两个指针adrress相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆