why this code gives error
main()
{
int *x;
*x = 5;
printf("%d",*x);
}
it works with some compiler but not with others. If I use malloc, then it works fine everywhere. Can you tell why?
Printable View
why this code gives error
main()
{
int *x;
*x = 5;
printf("%d",*x);
}
it works with some compiler but not with others. If I use malloc, then it works fine everywhere. Can you tell why?
Yes.
*x is supposed to point to some place in memory. At that place in memory is a variable of type int. Only you do not create any variable in memory for x to aim at.
Just declaring like that has x referring to nothing. malloc() gives it something to refer to.
Code:int main()
int y;
int *x;
x = &y;
*x = 5;
printf("%d %d\n",*x,y);
return 0;
}