Reputation: 1835
char str[]="Hello";
this allocates 6 bytes for the string , but if i write
char *str = "Hello";
will this overwrite data because it was just meant to store 1 char? So what i'm asking is that when i declare a string, but not initialize it (char str[12]; ) , do 12 bytes get reserved here or when i initialize it? And if they do get initialized here, so that means that in:
char *str;
only 1 byte gets reserved, but when i make it point to a string, doesn't that overwrite data beyond it's bounds?
Upvotes: 1
Views: 408
Reputation: 81409
char str[]="Hello";
You got that right, its an array of 6 char
s
char *str = "Hello";
That's a pointer to a string literal. Somewhere there is an array of 6 char
s and your variable str
is just pointing to it.
char *str;
This does not reserve anything, its a pointer pointing to an indeterminated place. When you make it point to a string, then it points to an array of char
s that lives somewhere else, there is no copy involved.
Upvotes: 0
Reputation: 283921
char *str;
does not reserve any data for content. It is a pointer, sized to hold a memory address.
char *str = "Hello";
6 bytes for { 'H', 'e', 'l', 'l', 'o', 0 }
already has been stored somewhere by the compiler. Now you are making a variable holding its address (pointing to it). The string content is not copied.
Upvotes: 2