两个指针的地址相同 [英] Addresses of two pointers are same

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

问题描述

#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.

您应该始终把 P P1 作为两个不同的指针(即使它们具有相同的内容)作为它们可以或可以不指向相同的地址。你不应该依赖于编译器优化。

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天全站免登陆