获取C中字符串常量的地址 [英] Get address of a string-constant in C

查看:575
本文介绍了获取C中字符串常量的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取C中字符串常量的地址。

  char * const MYCONST = StringString ; 

据我所知,const是保存在内存的文本/代码段中的。
当我尝试获取MYCONSt中第一个元素的地址时:

  printf(%p\n ,&(MYCONST)); 

结果我得到0x7fff15342e28,它在堆栈中,而不在Text / Code段中。
有人可以帮我获取C中字符串常量的地址吗?



// edit
我找不到正确的答案到目前为止:当我写

  char * const MYCONST1 = StringString; 
printf( MYCONST1的地址:%p\n,MYCONST1);

char * const MYCONST2 = StringString;
printf( MYCONST2的地址:%p\n,(void *)MYCONST2);

这是输出:



地址MYCONST1的地址:0x400b91



MYCONST2的地址:0x400b91



但是它们应该具有不同的地址,因为两者不同常数。
结果长度为7而不是像区域设置变量那样为0x7fffa5dd398c时,有人能解释我吗?



谢谢!

解决方案

Q: //编辑到目前为止,我找不到正确的答案:写时

  char * const MYCONST1 = StringString; 
printf( MYCONST1的地址:%p\n,MYCONST1);

char * const MYCONST2 = StringString;
printf( MYCONST2的地址:%p\n,(void *)MYCONST2);

这是输出:

  MYCONST1的地址:0x400b91 

MYCONST2的地址:0x400b91

但是它们应该有不同的地址,因为这些是不同的常量。






A:因为两个指针都指向相同的字符串文字。编译器进行优化,让它们共享相同的数据,从而共享相同的地址。尝试使用

  gcc program_name.c -O 


看看。您会看到不同的地址。



相对:两个指针的地址相同


I would like to get the address of an string-constant in C.

 char * const MYCONST = "StringString";

As far as I know consts are "saved" in the Text/Code Segment of the memory. When I try to get the address of the first element in MYCONSt:

 printf("%p\n",&(MYCONST));

As result I get 0x7fff15342e28, which is in the stack and not in the Text/Code segement. Can anybody please help me get the address of a string-constant in C?

//edit I can't find the correct answer so far: When I write

  char * const MYCONST1 = "StringString";
  printf("Address of MYCONST1: %p\n",MYCONST1);

  char * const MYCONST2 = "StringString";
  printf("Address of MYCONST2: %p\n",(void*)MYCONST2);

this is the output:

Address of MYCONST1: 0x400b91

Address of MYCONST2: 0x400b91

But they should have different addresses, because the are different constants. Can anybody explain me while the result has a length of seven and not 0x7fffa5dd398c like a locale variable.

Thanks!

解决方案

Q: //edit I can't find the correct answer so far: When I write

char * const MYCONST1 = "StringString";
printf("Address of MYCONST1: %p\n",MYCONST1);

char * const MYCONST2 = "StringString";
printf("Address of MYCONST2: %p\n",(void*)MYCONST2);

this is the output:

Address of MYCONST1: 0x400b91

Address of MYCONST2: 0x400b91

But they should have different addresses, because the are different constants.


A: Since both the pointers point to same string literal. Compiler optimizes and let them share the same data and hence same address. Try compiling your code with

gcc program_name.c -O 

and see. You will see the addresses different.

Relative: Addresses of two pointers are same

这篇关于获取C中字符串常量的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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