Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c structs, pointer and memory allocation for fields

Tags:

c

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.

like image 561
Dervin Thunk Avatar asked Jul 10 '13 18:07

Dervin Thunk


People also ask

Do you need to allocate memory for a struct in C?

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() .

Will memory be allocated for a structure if declare a structure pointer?

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.

How do you allocate memory for pointer in structure?

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 .

How structs are organized in memory by C?

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.


2 Answers

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.

like image 171
P.P Avatar answered Sep 20 '22 13:09

P.P


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.

like image 28
Joey van Hummel Avatar answered Sep 21 '22 13:09

Joey van Hummel