2

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;

3
  • 3
    array is the address of the array. Commented Jul 17, 2013 at 11:11
  • 1
    array is not actually an address of the array, rather decays to a pointer to the first element in the array which is equal to the address of the array. Pls correct if am wrong Commented Jul 17, 2013 at 11:34
  • This: `int array[] = {conv_number};' also makes a one-element array, which isn't very useful. Commented Jul 17, 2013 at 15:11

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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

1 Comment

Actually printing the address should done with %p and not %d.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.