I'm very new to C, but have no idea why this program breaks. The program compiles and runs if I remove the lines that have to do with i
, but if I assign i
, I can no longer assign anything to *ptr
without the program breaking.
int main(void)
{
int i;
int *ptr;
i = 2;
*ptr = 5;
printf("%d",*ptr);
}
The key is you cannot use a pointer until you know it is assigned to an address that you yourself have managed, either by pointing it at another variable you created or to the result of a malloc call.
No, we don't have any kind of Pointer in Python language. The objects are passed to function by reference. The mechanism used in Python is exactly like passing pointers by the value in C.
You can only reference objects in Python. Lists, tuples, dictionaries, and all other data structures contain pointers.
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))
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With