![](/img/trans.png)
[英]Is it possible to printf the memory address of the first element of an array in C?
[英]How to printf a memory address in C
我的代码是:
#include <stdio.h>
#include <string.h>
void main()
{
char string[10];
int A = -73;
unsigned int B = 31337;
strcpy(string, "sample");
// printing with different formats
printf("[A] Dec: %d, Hex: %x, Unsigned: %u\n", A,A,A);
printf("[B] Dec: %d, Hex: %x, Unsigned: %u\n", B,B,B);
printf("[field width on B] 3: '%3u', 10: '%10u', '%08u'\n", B,B,B);
// Example of unary address operator (dereferencing) and a %x
// format string
printf("variable A is at address: %08x\n", &A);
我正在使用Linux mint中的终端进行编译,当我尝试使用gcc进行编译时,出现以下错误消息:
basicStringFormatting.c: In function ‘main’:
basicStringFormatting.c:18:2: warning: format ‘%x’ expects argument
of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("variable A is at address: %08x\n", &A);
我要做的就是在变量A的内存中打印地址。
使用格式说明符%p
:
printf("variable A is at address: %p\n", (void*)&A);
标准要求%p
说明符的参数类型为void*
。 由于printf
是可变函数,因此没有从T *
到void *
隐式转换,这对于C中的任何非可变函数都将隐式发生。因此,需要强制转换。 引用标准:
7.21.6格式化的输入/输出功能(C11草案)
p参数应为指向void的指针。 指针的值以实现定义的方式转换为一系列打印字符。
而您正在使用%x
,它需要unsigned int
而&A
是int *
类型。 您可以从手册中了解有关printf的格式说明符。 printf中的格式说明符不匹配会导致未定义的行为 。
使用%x
和长度说明符来打印int
或unsigned int
而不使编译器抱怨转换的一种解决方法是使用malloc:
unsigned int* D = malloc(sizeof(unsigned int)); // Allocate D
unsigned int D_address = *((unsigned int*) &D); // D address for %08x without warning
*D = 75; // D value
printf("variable D is at address: %p / 0x%08x with value: %u\n", D, D_address, *D);
另外,您可以使用gcc -w
标志进行编译以禁止显示这些转换警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.