[英]Wrong result from the conversion in an array
Let's say that I have 让我们说我有
char number[2] = "2";
In my code I get number 2 as a string that's why i have char. 在我的代码中,我得到数字2作为字符串,这就是为什么我有char。 Now with the usage of atoi I convert this char to int
现在使用atoi我将此char转换为int
int conv_number;
conv_number = atoi(number);
printf("Result : %d\n", conv_number);
which returns me Result : 2. Now I want to put this value in an array and print the result of the array.So I wrote 返回结果:2。现在我想把这个值放在一个数组中并打印数组的结果。所以我写了
int array[] = {conv_number};
printf("%d\n",array);
Unfortunately my result is not 2 but -1096772864. 不幸的是我的结果不是2而是-1096772864。 What am I missing;
我错过了什么;
You're missing that your array
is int[]
not int
, which is the expected second argument for printf
when you use the digit format parameter %d
. 您错过了您的
array
是int[]
而不是int
,这是使用数字格式参数%d
时printf
的预期第二个参数。
Use printf("%d\\n",array[0])
instead, since you want to access the first value in your array. 请改用
printf("%d\\n",array[0])
,因为您要访问数组中的第一个值。
In this circumstances array
in your printf
expression behaves as int*
. 在这种情况下,
printf
表达式中的array
表现为int*
。 You would get the same result if you were to use printf("%d\\n",&array[0])
, aka the address of the first element. 如果你要使用
printf("%d\\n",&array[0])
,也就是第一个元素的地址,你会得到相同的结果。 Note that if you're really interested in the address use the %p
format specifier instead. 请注意,如果您真的对地址感兴趣,请改用
%p
格式说明符。
in the expression printf("%d\\n",array);
在表达式
printf("%d\\n",array);
, array is an array (obviously) of int, which is similar to an int*
. ,array是一个int(显然)的数组,类似于
int*
。 the value of array
is not the value of the first cell (eg. array[0]) but decays to the array's address. array
的值不是第一个单元格的值(例如,数组[0]),而是衰减到数组的地址。
If you run your code multiple times, you'll probably have different values (the array location will vary from one run to an other) 如果多次运行代码,则可能会有不同的值(阵列位置会因一次运行而异)
You have to write : printf("%d\\n",array[0]);
你必须写:
printf("%d\\n",array[0]);
which is equivalent to printf("%d\\n",*array);
这相当于
printf("%d\\n",*array);
You are printing base address of your array. 您正在打印阵列的基地址。 Instead of that you need to print value at that array address.
而不是你需要在该阵列地址打印值。 like,
喜欢,
printf("%d",array[0]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.