Code:
#include <stdio.h>
int main() {
char *str;
char i = 'a';
str = &i;
str = "Hello";
printf("%s, %c, %x, %x", str, i, str, &i);
return 0;
}
I get this output:
Hello, a, 403064, 28ff0b
I have following two doubts:
How can I store a string without allocating any memory for it.
str
is a character pointer and is pointing to where char variablei
. When I addstr = "Hello";
aren't I using5
bytes from that location4
of which are not allocated?Since, I code
str = &i;
shouldn'tstr
and&i
have same value when I printf them? When I remove thestr = "Hello";
statementstr
and&i
are same. And ifstr
and&i
are same then I believe when I saystr = "Hello"
it should overwrite'a'
with'H'
and the rest'ello\0'
come into the subsequent bytes.I believe the whole problem is with
str = "Hello"
statement. It doesn't seem to be working like what I think.
Please someone explain how it works??