-2
int func(int a[]);
int main()
{
  int c = 21;  
  int *b;
  b=&c;
  printf("%d",b);
  func(b);
   
    return 0;
}

int func(int a[]){
    printf("\n%d",(a));
    printf("\n%d",*(a));
    printf("\n%d",(a[0]));
    printf("\n%d",(a[1]));
    printf("\n%d",(a[2]));
}

this is something I'm trying to understand how these pointers work with arrays. this is the output.

-680548828
-680548828
21
21
-680548828
32767

the first two 680548828 and the two 21s I understand. simply printing a would be the first element of array a[]. a[0] is like writing *a. what I dont get is why a[1] would have 680548828 in it. a[1] is the element in the array after the element where the pointer to 21 is stored(a[0])? sorry for the confusion please help. Thank you.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
TheSlyOne
  • 43
  • 1
  • 6
  • 1
    You're not using a compatible format when printing the pointer. In particular, there is no reason to assume that a pointer and an `int` have the same size. Use `%p` to safely print a pointer value (and cast the pointer to `void *`). – Tom Karzes Aug 21 '20 at 05:17
  • There is no `a[1]` or`a[2]` because a points to a single int - which means you have undefined behavior. – John3136 Aug 21 '20 at 05:19
  • [How dangerous is it to access an array out of bounds?](https://stackoverflow.com/questions/15646973/how-dangerous-is-it-to-access-an-array-out-of-bounds) – Lundin Aug 21 '20 at 08:38

1 Answers1

3

In your code

printf("%d",b);

invokes undefined behaviour, as you;re trying to print a pointer using %d. The correct way would be to use

  • %p format specifier
  • cast the argument to void *

The same logic is applicable to the called function also, remember, an array name decays to the pointer to teh first element, basically yields a pointer type, in most of the cases (including this specific usage).

That said, you are trying to access invalid memory in the called function. You passed a pointer to one int, and in the called function, you're trying to access memory outside the memory region, by saying a[1], a[2] etc. You cannot do that. It again invokes undefined behaviour.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261