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

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

问题描述

#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);

请参阅此答案了解原因.

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

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