Lance Pollard
Lance Pollard

Reputation: 79360

If an struct initialized with null values takes up space

I am not too familiar with C, but I am wondering how structs are constructed in memory. Take for example this struct:

struct Books {
  char  title[50];
  char  author[50];
  char  subject[100];
  int   book_id;
};

int main() {
  struct Books Book1;
  struct Books Book2;
}

I'm wondering if you just initialize it like struct Books Book1;, if it will allocate memory for all the fields it has (title, author, etc.). If not, wondering what it does. I'm wondering how a programming language compiles a struct when the fields are null or not initialized.

If it is empty/blank/allocates no memory, then say you set it to this:

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

And then you unset it. Wondering if it clears the memory so it goes back to zero, or it keeps the memory allocated.

Upvotes: 0

Views: 710

Answers (1)

Barmar
Barmar

Reputation: 781716

struct Books Book1; is a variable declaration, not an initialization. All variable declarations allocate memory for the variable, there's nothing different about struct declarations. The amount of memory allocated is sizeof(struct Books).

If the variable is not initialized, it allocates memory, but the initial contents of the memory are implementation-dependent (unless it's a static variable, then it's as if every field were initialized to 0).

Global variables are allocated when the program starts; since they're also static, they will get default zero initialization if there's no initializer provided.

Local variables are allocated when the function or block is entered, and the memory allocation stays until the function or block is exited.

Upvotes: 2

Related Questions