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";
};
Thanks.
No. If you declare or typedef a struct type, the type exists for use with variables later on. Now that you have the type declared, variables can be allocated on the stack, or dynamically allocated using something like malloc() .
However, the declaration for a pointer to structure is only allocates memory for pointer NOT for structure. So accessing the member of structure we must allocate memory for structure using malloc() function and we could also give the address of the already declared structure variable to structure pointer.
To allocate the memory for n number of struct person , we used, ptr = (struct person*) malloc(n * sizeof(struct person)); Then, we used the ptr pointer to access elements of person .
Struct members are stored in the order they are declared. (This is required by the C99 standard, as mentioned here earlier.) If necessary, padding is added between struct members, to ensure that the latter one uses the correct alignment. Each primitive type T requires an alignment of sizeof(T) bytes.
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.
I am new to C but from what I think this could be just the same as
char *cThing;
cThing = "Things!";
where printf("%s\n", cThing);
would then print "Things!", except you're declaring the pointer in a struct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With