c structs, pointer and memory allocation for fields

c

Solution

struct c c1;
c1.name = "Ana";

You don't have allocate memory here because you are making the pointer `c1.name` point to a string literal and string literals have static storage duration. This is NOT similar to:

char name[] = "Anna";

Because in this case memory is allocated to store the sting literal and then the string literal `"Anna"` is copied into the array `name` . What you do with the struct assignment `c1.name = "Ana"` is similar to when you do:

char *name = "Anna";

i.e. make the pointer point to a string literal.

Problem

Suppose the following code: ``` struct c { char* name; }; int main(int argc, char *argv[]) { struct c c1; c1.name = "Ana"; printf ("%s\n",c1.name); return 0; } ``` My first reaction would have been to think that I needed to allocate some space, either on the heap, or by an explicit `char name[] = "Anna"`, but my example above works. Is the compiler just storing that string in the Data segment and pointing to it? In other words, is that like doing a ``` struct c { char* name = "Ana"; }; ```

Original source