在下面的代码中,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/