Why printing num
was okay but *num
resulted in segmentation fault?
When you say, int *num2=20;
. It is equivalent to
int *num; /* Type:(int*) num is a pointer to an integer and hence holds address of an integer object. */
num = 20; /* Type of the value assigned to num is (int).*/
You are assigning int
to int *
. You should have received a
warning: initialization makes pointer from integer without a cast[enabled by defaut]
num
points to the address '20
'. You have no idea even if that is a valid address.
Hence when you printed just num
you had no problems. But dereferencing, the address(20
) is invalid memory read , causes undefined behaviour and that resulted in segmentation fault.
Solution:
num
should hold a valid address. Do not take this risk by assigning some random address yourself.
Avoid that risk by either creating an object of type int
and assign num
to hold the address of it or just allocate memory for that. Like,
i):
int var = 20; /* var is a integer object holding the value 20 */
&
unary operator helps you get the address of the operand. Use &
with var
to get its address and since var
is an integer, store it in an integer pointer. In your case, num
.
int *num = &var; /* num is a pointer to var. Holds the address of var. */
ii):
int *num = malloc(sizeof *num);
*num = 20;