[英]Printf show the wrong number
char n[100];
int u[100];
int x[8];
scanf("%[^\n]",&n);
scanf("%d %d",&x,&u);
printf("%s\n",n); //print correct
printf("%d\n",x); //print not the exact number i input in scan
printf("%d\n",u);// print not the exact number i input in scan
if i input x and u for ex: 12345678 20 the output will print: random number如果我输入 x 和 u for ex: 12345678 20 输出将打印:随机数
For %[^\\n]
, scanf
expects a pointer to a char
(which is the first of enough char
to receive the string), but &n
is a pointer to an array of char
.对于%[^\\n]
, scanf
需要一个指向char
的指针(这是第一个足够接收字符串的char
),但&n
是一个指向char
数组的指针。 Change scanf("%[^\\n]",&n);
更改scanf("%[^\\n]",&n);
to scanf("%[^\\n]", n);
到scanf("%[^\\n]", n);
. . Although n
is an array of char
, when used like this, it is automatically converted to a pointer to its first element, so a pointer to a char
will be passed.尽管n
是一个char
数组,但当像这样使用时,它会自动转换为指向其第一个元素的指针,因此将传递指向char
的指针。
For %d
, scanf
expects a pointer to an int
, but &x
and &u
are pointers to arrays of int
.对于%d
, scanf
需要一个指向int
的指针,但&x
和&u
是指向int
数组的指针。 Change int u[100];
改变int u[100];
to int u;
给int u;
and int x[8];
和int x[8];
to int x;
到int x;
. . Then, in scanf("%d %d",&x,&u);
然后,在scanf("%d %d",&x,&u);
, pointers to int
will be passed. , 指向int
指针将被传递。
In printf("%s\\n",n);
在printf("%s\\n",n);
, for %s
, printf
expects a pointer to the first of several char
to print, and n
is automatically converted to a pointer to its first element, so this is correct. ,对于%s
, printf
需要一个指向要打印的几个char
的第一个的指针,并且n
会自动转换为指向其第一个元素的指针,所以这是正确的。
In printf("%d\\n",x);
在printf("%d\\n",x);
, for %d
, printf
expects an int
. ,对于%d
, printf
需要一个int
。 Previously, when x
was an array, this was passing a pointer to the first int
in the array.以前,当x
是一个数组时,它会传递一个指向数组中第一个int
的指针。 Then printf
may have been printing the pointer as if it were an int
, but a variety of things can go wrong with this.然后printf
可能已经将指针打印为一个int
,但是这可能会出现各种问题。 With the corrected definition of x
shown above, this will pass the value of x
instead of a pointer, so it will be correct.使用上面显示的更正的x
定义,这将传递x
的值而不是指针,因此它是正确的。
Similarly, printf("%d\\n",u);
同样, printf("%d\\n",u);
will be correct once the definition of u
is changed from an array to a single item.一旦u
的定义从数组更改为单个项目,就会正确。
Turn on warnings in your compiler and pay attention to them.在编译器中打开警告并注意它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.