Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong result from the conversion in an array

Tags:

arrays

c

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. Now with the usage of atoi I convert this char to 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

int array[] = {conv_number};
printf("%d\n",array);

Unfortunately my result is not 2 but -1096772864. What am I missing;

like image 818
dali1985 Avatar asked Mar 09 '26 17:03

dali1985


1 Answers

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.

Use printf("%d\n",array[0]) instead, since you want to access the first value in your array.

Further explanation

In this circumstances array in your printf expression behaves as int*. You would get the same result if you were to use printf("%d\n",&array[0]), aka the address of the first element. Note that if you're really interested in the address use the %p format specifier instead.

like image 166
Zeta Avatar answered Mar 12 '26 09:03

Zeta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!