有关printf参数的问题. C/C ++ [英] A question about printf arguments. C/C++
问题描述
我们有以下代码片段:
char tab[2][3] = {'1', '2', '\0', '3', '4', '\0'};
printf("%s\n", tab);
而且我不明白为什么在调用我确实得到了警告但没有错误,程序运行正常.打印'printf
时我们没有得到错误/警告.12
'.
printf
期望使用类型为char *
的参数,即指向char
的指针.因此,如果我声明了char arr[3]
,则arr
是包含char
的存储单元的地址,因此,如果我用它调用了printf
,它将衰减为指向char 的指针. ,即char *
.
类似地,tab
是包含3个字符的数组类型的存储单元的地址,而该存储单元的地址又包含char
,因此tab
将衰减为char **
,这应该是个问题,因为printf
期望的是char *
.
And I don't understand why we don't get an error / warning in the call to I DO get a warning but not an error, and the program runs fine. It prints 'printf
.12
'.
printf
is expecting an argument of type char *
, i.e. a pointer to char
. So if I declared char arr[3]
, then arr
is an address of a memory unit which contains a char
, so if I called printf
with it, it would decay to pointer to char, i.e. char *
.
Analogously, tab
is an address of a memory unit that contains the type array of 3 char's which is in turn, an address of memory unit contains char
, so tab
will decay to char **
, and it should be a problem, since printf
is expecting a char *
.
有人可以解释这个问题吗?
Can someone explain this issue?
我得到的警告是:
a.c:6: warning: char format, different type arg (arg 2)
The warning I get is:
a.c:6: warning: char format, different type arg (arg 2)
推荐答案
示例来源
#include <stdio.h>
int main( void ) {
char tab[2][3] = {'1', '2', '\0', '3', '4', '\0'};
printf("%s\n", tab);
return 0;
}
编译警告
$ gcc test.c
test.c: In function ‘main’:
test.c:5: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char (*)[3]’
指针就是指针
printf
的%s
参数向函数指示它将接收指针(指向字符串). C中的字符串只是由ASCII-Z终止的一系列字节. tab[2][3]
变量是一个指针.一些编译器会发出有关指针不匹配的警告.但是,该代码仍应打印出12
,因为printf
的代码会从给定的指针开始遍历内存(一直打印字符),直到找到零字节为止.从tab
变量表示的地址开始,在内存中连续设置1、2和\ 0.
The %s
argument to printf
indicates to the function that it will be receiving a pointer (to a string). A string, in C, is merely a series of bytes terminated by an ASCII-Z. The tab[2][3]
variable is a pointer. Some compilers will issue a warning about the pointer mismatch. However, the code should still print out 12
because printf
's code traverses memory starting at the pointer it was given (printing characters as it goes) until it finds a zero byte. The 1, 2, and \0 are contiguously set in memory, starting at the address represented by the tab
variable.
实验
作为实验,编译并运行以下代码会发生什么:
As an experiment, what happens when you compile and run the following code:
#include <stdio.h>
int main( void ) {
char tab[2][3] = {'1', '2', '\0', '3', '4', '\0'};
printf("%s\n", tab[1]);
return 0;
}
不要害怕尝试.看看您是否可以根据自己现在所知道的来得出答案.您现在将如何根据实验参考tab
摆脱警告并仍然显示12
?
Don't be afraid of experimenting. See if you can come up with the answer based on what you now know. How would you reference tab
now (in light of the experiment) to get rid of the warning and still display 12
?
这篇关于有关printf参数的问题. C/C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!