Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers confusion in C

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";
like image 207
RadicalOne Avatar asked Sep 11 '26 21:09

RadicalOne


1 Answers

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);
like image 120
simonc Avatar answered Sep 15 '26 04:09

simonc