Help in Initializing values to Pointers

Revision en1, by mohitmohak, 2020-09-19 10:55:00

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 by 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.

Tags #pointers, #c

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English mohitmohak 2020-09-19 10:55:00 620 Initial revision (published)