c - 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 数组的整个单元。
解决方案
您必须单独打印每个值,如下所示:
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 的代码中阅读详细信息。
推荐阅读
- gis - 了解 openaddresses 数据格式
- javascript - 用d3绘制散点图
- .net - json newtonsoft 序列化记录合并
- c - GCC:在获取地址时取消引用“void *”指针
- kotlin - 如何使用 Koin 依赖注入 (Kotlin) 检索与给定类型匹配的所有实例
- java - 对字符串进行排序时,数组中的字符被删除
- c++ - OpenSSL - 通过代码生成的数字签名与命令行上生成的签名不匹配
- c - Code::Blocks:带有指针 FILE 参数的函数(和函数原型)出错
- html - 为什么div背景不透明?
- json - 如何通过 VB.net 传递一个复杂的 JSON 对象来调用 Rest API