0

how big is this structure in Bytes? I would expect 104 Bytes im summary, 52Byte for record[0] and 52Byte for record[1] but it is 112Byte in summery and 56Bytes each element of record[].

Can somebody explain why it is so? On my system (Win64) a char = 1, int=4 and double = 8 Byte.

#include <stdio.h>
#include <string.h>

struct employee{
   int id;
   char firstName[20];
   char lastName[20];
   double salary;
};

const int MAX_RECORDS = 2;

int main(void)
{
   struct employee record[MAX_RECORDS];

   for(int i=0; i<MAX_RECORDS; i++) {
        printf("Enter ID: ");
        scanf("%d", &record[i].id);
        printf("Enter first name: ");
        scanf("%s", record[i].firstName);
        printf("Enter last name: ");
        scanf("%s", record[i].lastName);
        printf("Enter salary: ");
        scanf("%lf", &record[i].salary);
   }

   for(int i=0; i<MAX_RECORDS; i++){
        printf(" %d. Record of employee:\t", i+1);
        printf("ID: %d, ", record[i].id);
        printf("Name: %s %s, ", record[i].firstName, record[i].lastName);
        printf("Salary: %.2f\n", record[i].salary);
        printf("Size: %d\n", sizeof(record));     // 112
        printf("Size: %d\n", sizeof(record[0]));  // 56
        printf("Size: %d\n", sizeof(record[1]));  // 56
        printf("Size: %d\n", sizeof(char));       // 1
        printf("Size: %d\n", sizeof(int));        // 4
        printf("Size: %d\n", sizeof(double));     // 8
   }
   return 0;
}
Heimo
  • 39
  • 2
  • 4
    Does this answer your question? [Struct memory layout in C](https://stackoverflow.com/questions/2748995/struct-memory-layout-in-c),, and more specific: [4 padding bytes are added at the end so that the overall struct is a multiple of 8 bytes.](https://stackoverflow.com/questions/2748995/struct-memory-layout-in-c#:~:text=4%20padding%20bytes%20are%20added%20at%20the%20end%20so%20that%20the%20overall%20struct%20is%20a%20multiple%20of%208%20bytes.%20I%20checked%20this%20on%20a%2064%2Dbit%20system%3A%2032%2Dbit%20systems%20may%20allow%20structs%20to%20have%204%2Dbyte%20alignment.) – Luuk Jan 23 '23 at 17:06

0 Answers0