I've just started learning C and I've been running some simple programs using MinGW for Windows to understand how pointers work. I tried the following:
#include <stdio.h> int main(){ int *ptr; *ptr = 20; printf("%d", *ptr); return 0; }
which compiled properly but when I run the executable it doesn't work - the value isn't printed to the command line, instead I get an error message that says the .exe file has stopped working.
However when I tried storing the value in an int variable and assign *ptr to the memory address of that variable as shown below:
#include <stdio.h> int main(){ int *ptr; int q = 50; ptr = &q; printf("%d", *ptr); return 0; }
it works fine.
My question is, why am I unable to directly set a literal value to the pointer? I've looked at tutorials online for pointers and most of them do it the same way as the second example.
Any help is appreciated.
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.
You can assign 0 into a pointer: ptr = 0; The null pointer is the only integer literal that may be assigned to a pointer.
When you place an ampersand in front of a variable you will get it's address, this can be stored in a pointer vairable. When you place an asterisk in front of a pointer you will get the value at the memory address pointed to.
Pointer assignment between two pointers makes them point to the same pointee. So the assignment y = x; makes y point to the same pointee as x . Pointer assignment does not touch the pointees. It just changes one pointer to have the same reference as another pointer.
The problem is that you're not initializing the pointer. You've created a pointer to "anywhere you want"—which could be the address of some other variable, or the middle of your code, or some memory that isn't mapped at all.
You need to create an int
variable somewhere in memory for the int *
variable to point at.
Your second example does this, but it does other things that aren't relevant here. Here's the simplest thing you need to do:
int main(){ int variable; int *ptr = &variable; *ptr = 20; printf("%d", *ptr); return 0; }
Here, the int
variable isn't initialized—but that's fine, because you're just going to replace whatever value was there with 20
. The key is that the pointer is initialized to point to the variable
. In fact, you could just allocate some raw memory to point to, if you want:
int main(){ void *memory = malloc(sizeof(int)); int *ptr = (int *)memory; *ptr = 20; printf("%d", *ptr); free(memory); return 0; }
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