Sensei said:
Of course, but it's legal
I meant, int instead of void, as somebody said correctly.
That the first is statically allocated and the second uses a non
allocated memory? I was always taught not to use the second form, since
you can access random memory.
Both
char *p = "yes";
and
char *p;
p = "yes";
do the exact same thing: the string literal "yes" is statically
allocated in non-writable memory, and its pointer value is assigned to
p (not to a location pointed to by p). For the sake of illustration,
assume that the string literal "yes" is stored at memory location
0x8000. Then the statements above are equivalent to
char *p = 0x8000;
and
char *p;
p = 0x8000;
It's not any different from doing
int i;
int *p;
p = &i;
You wouldn't say that last assignment was a problem, would you?
What you *don't* want to do is anything like
char *p;
strcpy(p, "yes");
or
char *p;
p[0] = 'y';
p[1] = 'e';
p[2] = 's';
because then you are attempting to write to the location that p *points
to*, which is invalid.
The only hitch with
char *p = "yes";
is that string literals are not writable, so doing something like
char *p = "yes";
strcpy(p, "no");
or
p[0] = 'Y';
would be illegal.
[snip]
p has been allocated, what do you think the definition did? Do you
mean the space to which p points has not been allocated? If so, that
is also incorrect.
p yes, but afaik just the pointer and not the chars... wouldn't be
correct to use
char *p = "balh"; OR char p[] OR p[aNumber]
or malloc p before allocating space for the string.
The space for the string has *already been allocated* by virtue of the
string literal; somewhere in (non-writable) memory is a char buffer
with the contents "yes", and the location of that buffer is what's
being assigned to p. Whether it's assigned as an initializer in the
definition of p or as a separate assignment statement doesn't matter.