55

当我运行此代码时。

#include <stdio.h>

void moo(int a, int *b);

int main()
{
    int x;
    int *y;

    x = 1;
    y = &x;

    printf("Address of x = %d, value of x = %d\n", &x, x);
    printf("Address of y = &d, value of y = %d, value of *y = %d\n", &y, y, *y);
    moo(9, y);
}

void moo(int a, int *b)
{
    printf("Address of a = %d, value of a = %d\n", &a, a);
    printf("Address of b = %d, value of b = %d, value of *b = %d\n", &b, b, *b);
}

我的编译器中不断出现此错误。

/Volumes/MY USB/C Programming/Practice/addresses.c:16: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘int *’
/Volumes/MY USB/C Programming/Practice/addresses.c:17: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘int **’
/Volumes/MY USB/C Programming/Practice/addresses.c:17: warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘int *’
/Volumes/MY USB/C Programming/Practice/addresses.c: In function ‘moo’:
/Volumes/MY USB/C Programming/Practice/addresses.c:23: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘int *’
/Volumes/MY USB/C Programming/Practice/addresses.c:24: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘int **’
/Volumes/MY USB/C Programming/Practice/addresses.c:24: warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘int *’

你可以帮帮我吗?

谢谢

布拉格曼

4

5 回答 5

99

你想用来%p打印一个指针。从规范:

p 参数应是指向 的指针void。指针的值以实现定义的方式转换为打印字符序列。

不要忘记演员阵容,例如

printf("%p\n",(void*)&a);
于 2011-03-12T23:57:46.877 回答
9

当您打算打印任何变量或指针的内存地址时,使用%d不会完成这项工作并且会导致一些编译错误,因为您试图打印出数字而不是地址,即使它确实有效,你会有一个意图错误,因为内存地址不是数字。该值0xbfc0d878肯定不是数字,而是地址。

你应该使用的是%p. 例如,

#include<stdio.h>

int main(void) {

    int a;
    a = 5;
    printf("The memory address of a is: %p\n", (void*) &a);
    return 0;
}

祝你好运!

于 2013-06-13T06:20:17.020 回答
1

要打印变量的地址,您需要使用%p格式。%d用于有符号整数。例如:

#include<stdio.h>

void main(void)
{
  int a;

  printf("Address is %p:",&a);
}
于 2018-03-20T01:48:00.767 回答
0

看起来你使用 %p: Print Pointers

于 2011-03-12T23:59:20.737 回答
0

我试过在线编译器 https://www.onlinegdb.com/online_c++_compiler

int main()
{
    cout<<"Hello World";
    int x = 10;
    int *p = &x;
    printf("\nAddress of x is %p\n", &x); // 0x7ffc7df0ea54
    printf("Address of p is %p\n", p);    // 0x7ffc7df0ea54

    return 0;
}
于 2020-04-22T14:02:00.130 回答