#include <stdio.h>
int main(){
char *name;
printf("Enter a name: ");
scanf("%[^\n]s", &name);
printf("%s", &name);
return 0;
}
Here, I created a dangling pointer i.e. doesn't point to any adress and I tried storing a string into it and i found that using an ampersand before pointer worked for I-O but i just don't know why. I'm just getting started with C.
Here is how the output looks
Enter a name: Joseph Tribbiani
Joseph Tribbiani
By using the ampersand &name
, you are actually taking the address of the variable name
, which is a pointer to char. Yes, name
doesn't point to any adress, but it's still a variable and it takes up space to store its value, just like an int
variable. Depending on your architecture, name
takes up 4 or 8 bytes. This means you can store bytes into this name
variable just you would any other variable.
Your code works because you are using the variable name
as a char array to store your input. You scanf
the string and store it to name
and then printf
it out. You can either input 4 or 8 one-byte chars before using up name
's size. (UPD: Thanks Andy in the comment, since scanf
adds a null termination byte, it's actually 3 or 7 chars. I totally forgot about that :p)
On my 64bit Ubuntu 20.10 with gcc 10.3.0, I got stack smashing error if I input more than 8 chars. However, if I input abcdefgh
and print out the value of name
(not &name
) using printf("%p", name)
, I will get 0x6867666564636261
. Recall that the ASCII code for the character a
is 97, aka 0x61. And since my pc uses Little Endian Byte Order, the least significant byte of 0x6867666564636261
is just 0x61
. This means 'a'
is stored at the first byte of name
, and 'b'
, 'c'
... follows, just like a char array.