指向不同字符串文字的两个char指针的地址相同 [英] Addresses of two char pointers to different string literals are same

查看:192
本文介绍了指向不同字符串文字的两个char指针的地址相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

int main()
{
    char * p = "abc";
    char * p1 = "abc";
    printf("%d %d", p, p1);
}

当我打印两个指针的值时,它正在打印相同的地址.为什么?

When I print the values of the two pointers, it is printing the same address. Why?

推荐答案

是否将两个具有相同内容的不同字符串文字放在相同的存储位置中,或者将不同的存储位置取决于实现.

Whether two different string literals with same content is placed in the same memory location or different memory locations is implementation-dependent.

您应该始终将pp1视为两个不同的指针(即使它们具有相同的内容),因为它们可能指向或不指向同一地址.您不应该依赖编译器优化.

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.

C11标准,6.4.5,字符串文字,语义

如果这些数组的数组不同,则不确定 元素具有适当的值.如果程序尝试执行 修改这样的数组,行为是不确定的.

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.


打印格式必须为%p:

  printf("%p %p", (void*)p, (void*)p1);

有关原因,请参见此答案.

这篇关于指向不同字符串文字的两个char指针的地址相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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