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

Joh*_*hv1 -1 c string constants

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

 char * const MYCONST = "StringString";
Run Code Online (Sandbox Code Playgroud)

据我所知,consts被"保存"在内存的文本/代码段中.当我试图获取MYCONSt中第一个元素的地址时:

 printf("%p\n",&(MYCONST));
Run Code Online (Sandbox Code Playgroud)

结果我得到0x7fff15342e28,它在堆栈中而不在文本/代码段中.任何人都可以帮我在C中获取字符串常量的地址吗?

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

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

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

这是输出:

MYCONST1的地址:0x400b91

MYCONST2的地址:0x400b91

但它们应该有不同的地址,因为它们是不同的常量.任何人都可以解释我,结果的长度为7,而不是0x7fffa5dd398c,就像一个locale变量.

谢谢!

das*_*ght 5

由于MYCONST已经是指针,因此您不需要&符号.所有你需要的是一个投来void*%p:

printf("%p\n",(void*)MYCONST);
Run Code Online (Sandbox Code Playgroud)

使用&符号,您可以打印MYCONST局部变量的地址(您还需要在void*那里进行转换,否则地址可能会错误地打印),这确实位于堆栈上.