首页 > 解决方案 > printf 数组的整个单元

问题描述

假设这样一段最少的代码:

#include <stdio.h>
int arr[3] = {1, 2, 3};
int *ptr = arr;
int main(void)
{
    printf("The value of arr is %d, the address of the arr is %ptr", *ptr, ptr);
}

得到它的输出:

$ ./a.out
The value of arr is 1, the address of the arr is 0x107d57018tr

我想打印整个数组单元,所以尝试在 printf 函数中替换%d为。 尽管如此,它仍然报告错误:%s

first_c_program.c:6:70: warning: format specifies type 'char *' but the argument has type 'int' [-Wformat]
    printf("The value of arr is %s, the address of the arr is %ptr", *ptr, ptr);
                                ~~                                   ^~~~
                                %d
1 warning generated.

我怎么能 printf 数组的整个单元。

标签: c

解决方案


您必须单独打印每个值,如下所示:

for (size_t i = 0; i < 3; i++)
  printf("%d", arr[i]);

printf("%d", *arr)将数组的第一个值打印为整数。它等价于printf("%d", arr[0]),printf("%d", arr[i])printf("%d", *(arr + i))是可互换的。printf("%ptr", arr)将数组的地址(即第一个值的地址)打印为地址。

正如其他人指出的那样,%s期望char *,见printf(3)。如果您有兴趣,printf它只是 的包装器vfprintf,它实现了一个跳转表,而跳转表又在write一系列 vtable 和宏之后以系统调用结束,而格式化的东西发生在vfprintf.c. 您可以在这篇博文和glibc 的代码中阅读详细信息。


推荐阅读