somu
somu

Reputation: 13

Way of structure memory allocation

struct Books {
   char  title[50];
};

int main( ) {

   struct Books Book1;       
   struct Books Book2;      

   strcpy( Book1.title, "C Programming");

   strcpy( Book2.title, "Telecom Billing");

   printf( "Book 2 title : %s\n", Book2.title);

   printf( "Book 1 title : %s\n", Book1.title);
  }

Here, everything got executed properly but I want to ask that how 'struct' is allocating memory for 'book2' without using any memory allocation function or any pointer?

Upvotes: 0

Views: 116

Answers (2)

ohe
ohe

Reputation: 3673

Your Books structure allocates, each time a book is instantiated (i.e. when you declare Book1 and Book2 in your main function) an array of 50 chars (50 bytes) that can be used to store the title.

To get a sense of how things work, try the same program with the following Books definition

struct Books {
    char * title
}

Upvotes: 0

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43508

Both Book1 and Book2 are automatic variables. They are automatically allocated once declared and automatically deallocated once they go out of scope. You must be very careful not to return any pointers to them once their function has returned.

On most contemporary architectures they will reside on the stack (unless the compiler puts them in registers). The allocation itself is very cheap as it only involves incrementing the stack pointer.

Upvotes: 3

Related Questions