0

I'm trying to compile and display the address of each value into the arrays.


int i[10] = {1,2,3,4,5,6,7,8,9,10}, x;
float f[10] = {1,2,3,4,5,6,7,8,9,10};
double d[10] = {1,2,3,4,5,6,7,8,9,10};

/*int *p_i = &i;                                                             
                                                                             
float *p_f = &f;                                                             
                                                                             
double *p_d = &d;*/

int main(void){
  printf("\n\tInteger\tFloat\tDouble");
  printf("\n=======================================");

  /* loop to show the address in each element that have the arrayes */
  for(x = 0; x < 10; x++){
    printf("\nElement %d\t%d\t%d\t%d", x+1, &i[x], &f[x], &d[x]);
    // printf("\nElement %d\t%d\t%d\t%d", x+1, p_i++, p_f++, p_d++);         
  }
  printf("\n=======================================\n");
}

I don't understand why if the syntax is right. Also I have search and the found code is almost the same.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
ButchBet
  • 11
  • 1
  • 5
    Change `%d` to `%p` for the pointers. – Devolus Apr 02 '21 at 16:37
  • `i[x]` is an `int`. `&i[x]` is a pointer to that `int`. If the `int` is what you want to print, then that's what you should pass to `printf()`. If the pointer is what you want to print then the correct directive is `%p`, not `%d`. Similar applies even more so for variables `f` and `d`: if you want to print the `float` and `double` then the corresponding directives should (both) be `%f`, and you should not use `&`. If you want to print the pointers then the directive should be `%p`. – John Bollinger Apr 02 '21 at 16:40
  • And don't forget to cast pointers to `void*`: `printf("\nElement %d\t%d\t%d\t%d", x+1, &i[x], &f[x], &d[x]);` -> `printf("\nElement %d\t%p\t%p\t%p", x+1, (void*)&i[x], (void*)&f[x], (void*)&d[x]);` – P.P Apr 02 '21 at 16:45
  • See [Correct format specifier to print pointer or address?](https://stackoverflow.com/q/9053658/1275169) – P.P Apr 02 '21 at 16:46
  • ButchBet, Do you want to print an `int` or a pointer? – chux - Reinstate Monica Apr 02 '21 at 16:53

1 Answers1

1

You are using incorrect conversion specifiers.

The conversion specifier %d expects an argument of the type int while you are supplying arguments of pointer types.

Instead of

printf("\nElement %d\t%d\t%d\t%d", x+1, &i[x], &f[x], &d[x]);

write

printf( "\nElement %d\t%p\t%p\t%p", 
        x+1, ( void * )&i[x], ( void * )&f[x], ( void * )&d[x] );

or

printf( "\nElement %d\t%p\t%p\t%p", 
        x+1, ( void * )( i + x ), ( void * )(f + x ), ( void * )( d + x ) );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335