简体   繁体   中英

c pointer being passed to a function

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM