简体   繁体   中英

c pointers segmentation fault

CASE 1:

#include <stdio.h>
int main()
{
 int a = 5,*p;
 *p = &a;
  printf("%d",*p);
 }

the above mentioned program gives the segmentation fault problem. but in the case 2 it works fine. CASE 2:

#include <stdio.h>
int main()
{
int a = 5,*p = &a;
printf("%d",*p);
}

can anyone please explain this problem. Thank you.

*p = &a;

Dereferences p and assigns &a to the memory location p is pointing to . The pointer is uninitialized, so dereferencing it yields undefined behavior (thus the segmentation fault).

int a = 5,*p = &a;

Defines a and p , where the asterisk doesn't indicate dereferencing but distinguishes a usual int definition from a int* pointer definition. The line is equivalent to

int a = 5;
int* p = &a;

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