c 打印指针指向的数组的地址

标签 c arrays string pointers memory-address

在下面的代码中,str是一个指针,存储数组Goodbye的地址。数组Goodbye的地址从4196004开始,指针*str2的值为-1226226648。我的问题是,有没有办法使用指针*str2打印数组Goodbye的地址?

我尝试了这行 printf("%d %d %s\n", *str2, str2, str2); 取消引用 str2 并打印 71 这是 H 的 ascii,但我如何打印地址 4196004

int main(int argc, char **argv) {

char str1[] = "Hello";
char *str2 = "Goodbye";

printf("%d %d %s\n", &str1, str1, str1);
printf("%p %d %s\n", &str2, str2, str2);

}

Output: 
-1226226640 -1226226640 Hello
-1226226648 4196004 Goodbye

最佳答案

您的代码调用了未定义的行为,因为您尝试在不使用%p的情况下打印地址

printf()提及:

p Pointer address

并且不要像你应该的那样转换为 void

所以,这样做:

printf("%p %p %s\n", (void*)&str1, (void*)str1, str1);
printf("%p %p %s\n", (void*)&str2, (void*)str2, str2);

可能的输出:

0x7ffddaf7e67a 0x7ffddaf7e67a Hello
0x7ffddaf7e670 0x4005c4 Goodbye

关于c 打印指针指向的数组的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46422464/

相关文章:

c++ - 如何将 "sort"程序的输出从子程序重定向到父程序

java - 如何将正则表达式与 String.split() 一起使用

c - 词提取C

c++ - 关于sizeof用法的问题

c - 在 C 中使用递归的数字总和

javascript - 将数组中的某些字符串大写

java - 替换groovy中的大字符串

java - 如何处理可能是也可能不是数组、可能是也可能不是基元数组的 Java 对象

c - 如何从 char 数组中检索 n 个字符

c# - 检查数组是否是多维的