首页 > 解决方案 > 为什么在尝试显示整数内存位置时会出现 clang 错误?

问题描述

我查看了与我的问题匹配的问题,但找不到答案。在创建了一个程序来显示整数“i”和“k”的内存位置后,它没有使用 clang 编译。使用 SoloLearn 的 IDE 时,它运行良好。

#include <stdio.h>

void test(int k);

int main() {
    int i = 0;

    printf("The address of i is %x\n", &i);
    test(i);
    printf("The address of i is %x\n", &i);
    test(i);

    return 0;
}

void test(int k) {
    printf("The address of k is %x\n", &k);
}

这些是我得到的错误。

memory.c:8:37: warning: format specifies type 'unsigned int' but the argument has type 'int *' [-Wformat]
        printf("The address of i is %x\n", &i);
                                    ~~     ^~
memory.c:10:37: warning: format specifies type 'unsigned int' but the argument has type 'int *' [-Wformat]
        printf("The address of i is %x\n", &i);
                                    ~~     ^~
memory.c:17:37: warning: format specifies type 'unsigned int' but the argument has type 'int *' [-Wformat]
        printf("The address of k is %x\n", &k);
                                    ~~     ^~
3 warnings generated.

我需要在 int 上签名吗?如果需要,我应该怎么做?

标签: cinteger

解决方案


如果要打印变量或内存位置的地址,则应使用%p格式说明符。例如

int i = 0;
printf("The address of i is %p\n", (void*)&i);/* %p format specifier expects argument of void* */ 

C标准:

(C11,7.21.6.1p8 格式化输入/输出函数)“p 参数应为指向 void 的指针。”


推荐阅读