Directly assigning values to C Pointers
c, pointers
Solution
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;
}
Problem
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.