Possible Duplicate:
Dynamic String Input – using scanf(“%as”)
strcmp with pointers not working in C
Is the following considered good code? Shouldn’t I have used malloc somewhere? I was able to compile this and it worked, but I feel like it shouldn’t have.
#include <stdio.h>
int main (void) {
char *name;
printf("Whats your name? ");
scanf("%s", &name);
printf("\nyour name is %s", &name);
return 0;
}
What happens if I want to modify name? How would I go about doing so?
Edit: I am really just looking for the most efficient and correct way to do this using pointers. I am assuming malloc is necessary.
nameis a pointer, and&namereturns the address of the variablename, so thescanfis putting the name you enter into the pointer itself.For example, if you enter
ABCthen the pointer will be 0x00434241 (if the CPU is little-endian) or 0x41434200 (if the CPU is big-endian), where 0x41 is the character code for ‘A’, 0x42 is the character code for ‘B’, etc.You should allocate memory into which the entered name can be stored and then pass a pointer to it to
scanf.Here’s an example allocating on the stack: