1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

sizeof for a class

Discussion in 'C' started by go4expert, Jun 4, 2007.

  1. go4expert

    go4expert Moderator

    Joined:
    Aug 3, 2004
    Messages:
    306
    Likes Received:
    7
    Trophy Points:
    0
    Code:
    Class A
    {
      int a;
      float b;
    };
    Now what will be the value of sizeof(A);
     
  2. tiger12506

    tiger12506 New Member

    Joined:
    Jun 6, 2007
    Messages:
    14
    Likes Received:
    0
    Trophy Points:
    0
    Check it out for yourself.
    "class" is not a keyword in C. A struct is basically the same thing. I do know that "class" in c++ is just a "struct" with a default of private...

    Code:
    #include <stdio.h>
    
    struct A {
      int a;
      float b;
    };
    
    int main() {
      printf("sizeof(int) = %d\n",sizeof(int));
      printf("sizeof(float) = %d\n",sizeof(float));
      printf("sizeof(struct A) = %d\n",sizeof(struct A));
    }
    
    I get:

    sizeof(int) = 4
    sizeof(float) = 4
    sizeof(struct A) = 8

    But those values could be different on different platforms. The trick is that usually the size of the items in the struct add up to the size of the struct itself
     
  3. go4expert

    go4expert Moderator

    Joined:
    Aug 3, 2004
    Messages:
    306
    Likes Received:
    7
    Trophy Points:
    0
    I just wanted to post something else. Something like

    Code:
    struct A
    {
      int a;
      double b;
    };
    Now check what will be the size of and you will see the difference and why I have put it here.
     

Share This Page