4

I am new to C and currently learning arrays. I have this code:

#include <stdio.h>
int main()
{   
    int available[6];
    for(int o=1; o<=3; o++){
        available[o]=20;
        printf("%d\n",&available[o]);
    }
    return 0;
}

Which is supposed to output (in my understanding):

20
20
20

Now the problem is that it outputs:

2293300
2293304
2293308

Am i missing a crucial part and did some silly mistake?. Any help will be appreciated.

user13539846
  • 425
  • 2
  • 5
  • 13

2 Answers2

5
   printf("%d\n",&available[o]);

Here you are printing the address, because & gives the address of the following value, change it to:

   printf("%d\n",available[o]);

to print the value inside the array.

Mike
  • 4,041
  • 6
  • 20
  • 37
1
printf("%d\n",&available[o]);

&available[o] is a pointer to the memory address of available[o].

You need to omit the & operator to gain the value of available[o], not its address.


Since you also provided an argument of wrong type (int *) for the %d conversion specifier which expects an argument of type int, the program invokes undefined behavior:

"d, i The int argument is converted to signed decimal in the style[-]dddd. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it is expanded with leading zeros. The default precision is1.The result of converting a zero value with a precision of zero is no characters."

Source: C18, 7.21.6.1/8 - "The fprintf function"


"If a conversion specification is invalid, the behavior is undefined. 288) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined."

"288) See "future library directions" (7.31.11)."

Source: C18, 7.21.6.1/9 - "The fprintf function"