如何在C中使用printf以及我的代码应该打印出来的是什么?

Ben*_*sen 3 c printf

我是C的新手,我正在试图弄清楚printf方法的作用.我有这么一点代码,当我使用%x时我一直都会遇到错误,例如printf(“a) %x\n”, px);x%是十六进制,我只是在这里使用了错误的类型还是其他的东西?我下面的代码应该打印出来的是什么?

int x = 10;
int y = 20;

int *px = &x;
int *py = &y;

printf(“a) %x\n”, px);
printf(“b) %x\n”, py);

px = py;

printf(“c) %d\n”, *px);
printf(“d) %x\n”, &px);

x = 3;
y = 5;

printf(“e) %d\n”, *px);
printf(“f) %d\n”, *py);
Run Code Online (Sandbox Code Playgroud)

Chr*_*ung 8

使用整数格式(%x,%d或类似物)来打印指针是不可移植的.因此,对于任何指针(px,py&px,但不是*px*py),您应该使用它%p作为您的格式.


And*_*Dog 5

它工作得很好,没有错误(除了错误的引号,即""而不是""但我想这就是你的浏览器所做的).

以下是代码的示例输出:

a) 22ff74
b) 22ff70
c) 20
d) 22ff6c
e) 5
f) 5
Run Code Online (Sandbox Code Playgroud)

在这里进行探索

int x = 10;
int y = 20;

int *px = &x;
int *py = &y;

// You're printing out the pointer values here, which are the memory addresses of the
// variables x and y, respectively. Thus this may print any reasonable number within
// the stack memory space.
printf("a) %x\n", px);
printf("b) %x\n", py);

// Both pointer now point to y...
px = py;

// ... so this will print the value of y...
printf("c) %d\n", *px);

// ...and this will print the address of px, which will probably but not necessarily
// be the (memory address of y - 4) because the stack grows down and the compiler
// allocates space for the variables one after another (first y, then px).
printf("d) %x\n", &px);

x = 3;
y = 5;

// Remember that both px and px point to y? That's why both *px and *py resolve to
// the value of y = 5.
printf("e) %d\n", *px);
printf("f) %d\n", *py);
Run Code Online (Sandbox Code Playgroud)

但无论如何,对于指针,你通常应该使用"%p"格式说明符而不是"%x",因为它是整数(可以是不同于指针的大小).

  • 关于有趣的报价的好点.不确定浏览器是否应该受到指责 - 更有可能使用MS Word作为文本编辑器.这肯定会产生编译器错误,这可能是OP获得的错误类型. (2认同)