Can't assign values to variable and pointer
You leave the pointer with uninitialized value. So when you dereference it (*ptr
), you access arbitrary place in memory, resulting in a segmentation fault.
Point ptr
at something by assigning to ptr
itself (not *ptr
) an address of a variable (like &i
) or some freshly allocated memory (like malloc(sizeof(int))
).
Here is the answer for C:
int main(void) {
int i;
int * ptr = (int *)malloc(sizeof(int));
i = 2;
*ptr = 5;
printfn("%d",*ptr);
free(ptr);
}
Alternatively you could for the i and *ptr assignment lines use something like:
int main(void) {
int i;
int * ptr;
i = 2;
ptr = &i;
printfn("%d",*ptr); // should print 2
}
Notice also that the free came out!!!