Thread: size of structure

  1. #1
    Registered User
    Join Date
    May 2021
    Posts
    61

    size of structure

    one int variable occupy 4 byte and one char variable occupy 1 byte. In my code I store one int and char variable using structure

    Code:
    #include <stdio.h>
    
    struct S
    {
        int x;
        char y;
    }s1;
         
    int main()
    {
        s1.x = 20;
        s1.y ='A';
      
        printf("Size of Structure : %d byte \n", sizeof(struct S));
        printf("Size of s1 : %d byte \n", sizeof(s1));
        printf("Size of s1.x : %d  byte\n", sizeof(s1.x));
        printf("Size of s1.x : %d byte \n", sizeof(s1.y));
      
        return 0;
    }
    Size of Structure : 8 byte
    Size of s1 : 8 byte
    Size of s1.x : 4 byte
    Size of s1.x : 1 byte



    How much memory does my code occupy ?

    Does structure code occupy 8 byte ?

    I think code should be occupy 5 bytes only 4 byte for int and 1 byte for char total five bytes

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,887
    > Does structure code occupy 8 byte ?
    Yes.

    > I think code should be occupy 5 bytes only 4 byte for int and 1 byte for char total five bytes
    Reality wins, it's 8 bytes.

    Read this for a better understanding.
    Data structure alignment - Wikipedia
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    I found the following link to be useful for my own understanding of how structs are arranged in memory: Struct declaration - cppreference.com
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Size of structure
    By skyr6546 in forum C Programming
    Replies: 5
    Last Post: 12-27-2019, 10:39 AM
  2. C structure size
    By CANcprogram in forum C Programming
    Replies: 2
    Last Post: 07-18-2017, 03:09 AM
  3. size of structure
    By Leone in forum C++ Programming
    Replies: 1
    Last Post: 02-11-2010, 08:56 AM
  4. Size of structure in bytes
    By Micko in forum C Programming
    Replies: 2
    Last Post: 11-29-2004, 10:09 AM
  5. SIze of structure
    By Juganoo in forum C Programming
    Replies: 4
    Last Post: 12-03-2002, 10:23 PM

Tags for this Thread