Size of a struct variable

• How big is the struct typed variable ???

• Sizeof:

 The sizeof operator can be used with any user-defined data type to find out how many bytes of memory space the variable will need.

Example:

 ``` /* ------------------------ Structure definition ------------------------ */ struct BankAccount { int accNum; double balance; }; int main(int argc, char *argv[]) { printf("sizeof(struct BankAccount) = %d\n", sizeof(struct BankAccount) ); } ```

Output:

 ``` sizeof(struct BankAccount) = 16 ```

• Example Program: (Demo above code)

How to run the program:

 Right click on link(s) and save in a scratch directory To compile:   gcc sizeof1.c To run:          ./a.out

• \$64,000 question:

• Wait a minute... didn't we learned that:

 ``` sizeof(int) = 4 sizeof(double) = 8 ```

• How is it that sizeof(struct BankAccount) = 16 ???

 ``` struct BankAccount { int accNum; // 4 bytes double balance; // 8 bytes }; ---------------- 12 bytes !!! ```

Should a struct BanAccount variable use 12 bytes ????

• There are memory address alignment requirements in the computer hardware (the manifacturer set these requirements to make the memory operations efficient)

• Commonly used requirments:

 A double typed variable must be located at a memory address that is divisible by 8 An int typed variable (and a float typed variable) must be located at a memory address that is divisible by 4 A short typed variable must be located at a memory address that is divisible by 2 A char typed variable can be located at any memory address that

• In order to store a struct BankAccount, the C compiler must use the following storage format:

• Experiment that show the memory address alignment requirement:

 ``` struct s1 { char a; int d; }; struct s2 { char a; char b; int d; }; struct s3 { char a; char b; char c; int d; }; int main(int argc, char *argv[]) { printf("sizeof(struct s1) = %d\n", sizeof(struct s1) ); printf("sizeof(struct s2) = %d\n", sizeof(struct s2) ); printf("sizeof(struct s3) = %d\n", sizeof(struct s3) ); } ```

Output:

 ``` sizeof(struct s1) = 8 sizeof(struct s2) = 8 sizeof(struct s3) = 8 ```

Explanation:

• The variables of these 3 structures are stored in the following manner:

That's why all 3 structures will use 8 bytes to store their variables.

• Example Program: (Demo above code)

How to run the program:

 Right click on link(s) and save in a scratch directory To compile:   gcc sizeof2.c To run:          ./a.out

• Note: reference (pointer) variables to struct typed variables

• Teaching Note:

 I will delay the discussion of reference (= pointer) variables to struct variables This topic will be discusses after I discussed the other kinds of user defined types in C (You can defined reference variables that point to variables of any of the user-defined data types.)