Review: C's struct and Java's object

  • The struct definition in C is similar to a class definition in Java:

      C's struct Java's class
       struct BankAccount      
       { 
          int   ID;
          float balance;                  
       } ;
      
      
      
      
      
      
       public class BankAccount    
       {
          public int   ID;
          public float balance;
      
          public void deposit(double x)
          {
              balance += x;
          }
       }
      

  • Differences:

      1. No access protection of member fields in a C's struct

      2. A struct does not contain any (member) function definitions

Determine the memory usage of a data type  

  • The sizeof operator can be used with a user-defined data type (= struct) to find out how many bytes of memory space the struct variable will need.

  • Example:

    struct BankAccount  // I define struct here for brevity
    {
       int    accNum;      // 4 bytes
       double balance;     // 8 bytes ---> total = 12 bytes
    };
        
    int main(int argc, char *argv[])
    {
       printf("sizeof(struct BankAccount) = %d\n",        
                        sizeof(struct BankAccount) ); // 16 bytes
    } 

    Notice:

    • The total memory needed is not equal to the sum of the number of bytes in the variable !!

DEMO: demo/C/set2/sizeof1.c --- can you explain the gap between accNum and balance ? ()

Why is there a gap between member variables in a struct (object)

  • Due to the way the computer memory is constructed:

      • There are memory address alignment requirements to make the memory operations more efficient

  • The memory alignment requirments:

      • A double typed variable must be located at a memory address that is divisible by 8

      • An int typed variable or 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

Why is there a gap between member variables in a struct (object)

  • Member variables in a struct typed variable are stored sequentially in memory

  • Suppose the C compiler stores the member variable accNum at address 5000:

     

Why is there a gap between member variables in a struct (object)

  • Member variables in a struct typed variable are stored sequentially in memory

  • The C compiler cannot place the variable balance at address 5004:

    because 5004 is not divisible by 8 !

Why is there a gap between member variables in a struct (object)

  • Member variables in a struct typed variable are stored sequentially in memory

  • The C compiler must place the variable balance at address 5008:

    because 5008 is divisible by 8 !