Help in Initializing values to Pointers

I was trying to assign an integer to a pointer directly and received error of segmentation fault.
Code:

#include <stdio.h>
int main() {
int *p;
*p=4;
printf("%d",*p);
return 0;
}

However, when assigned pointer the address of a integer variable. And then changed the values from using value at operator it ran successfully.
Code:

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

Can anyone explain why cannot we assign a value to pointer without assigning it a address.
Thanks.

bro first u have to tell the pointer , for which variable it has to point ? in first test case u make pointer *p now compiler don’t know for which variable p points .

Go watch C tutorials bu saurabh shukla ji sir , on youtube.

When you are declaring

int *p; // It is basically pointing to some random memory location.
and,
while dereferencing it via * operator , it can be an illegal operation.

So the compiler avoid such kind of ambiguity to happen

C_by_saurabh_shukla_sir from video 46 to 52 in playlist

not so good advice

1 Like