dali1985
dali1985

Reputation: 3323

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. 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;

Upvotes: 2

Views: 97

Answers (3)

Zeta
Zeta

Reputation: 105885

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.

Upvotes: 9

johan d
johan d

Reputation: 2863

in the expression printf("%d\n",array);, array is an array (obviously) of int, which is similar to an int*. the value of array is not the value of the first cell (eg. array[0]) but decays to the array's address.

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]); which is equivalent to printf("%d\n",*array);

Upvotes: 2

Chinna
Chinna

Reputation: 4002

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]);

Upvotes: 1

Related Questions