i'm new to programming in C, and I've been thinking about this problem for quite some time now:
char* name;
scanf("%s", name);
Why doesn't this work? For example, if I type in "Hello", the program just gives me an error. But isn't the above code the exact same thing as this?
char* name = "Hello";
char* name;
declares a pointer but doesn't initialise it to point to memory you have allocated. Attempts to write to it using scanf result in undefined behaviour and may well crash.
char* name = "Hello";
declares a pointer and initialises it to point to a string literal. String literals may be stored in read-only memory so you should think of this as having type const char*.
So, if you want to assign a string at run-time, neither of these approaches would work. You would instead have to allocate memory for a char array then use scanf (or fgets, readline, etc.) to write a string to that memory
char name[20];
scanf("%19s", name);
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