Thread: how much memory structure take in code

  1. #1
    Registered User
    Join Date
    May 2017
    Posts
    113

    how much memory structure take in code

    I am confused with structure size

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

    one integer variable takes 4 bytes and one char variable takes 1 bytes so total size of structure should be 5 bytes but program gives 8 bytes
    so how much memory structure take in code ?
    Last edited by abhi143; 11-29-2019 at 07:28 PM.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,511
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    May 2017
    Posts
    113

    size of structure is 12 bytes and size of structure member is 4 + 4 +1 = 9 but compiler allocate extra 3 bytes that's we call padding

    Code:
    #include <stdio.h> struct point
    {
        int x;
        int y;
        char z;
        
    }s1;
         
    int main()
    {
        s1.x = 20;
        s1.y =10;
        s1.z = 'a';
         
     printf("s1.x= %d \n", s1.x);
     printf("s1.y= %d \n", s1.y);
     printf("s1.z= %c \n", s1.z);
      
     printf("Size of struct: %d \n", sizeof(struct point)); 
     printf("Size of x: %d \n", sizeof(s1.x)); 
     printf("Size of y: %d \n", sizeof(s1.y)); 
     printf("Size of z: %d \n", sizeof(s1.z)); 
        return 0;
    }

    s1.x= 20
    s1.y= 10
    s1.z= a
    Size of struct: 12
    Size of x: 4
    Size of y: 4
    Size of z: 1
    Last edited by abhi143; 11-30-2019 at 12:37 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 11-09-2019, 05:37 AM
  2. How does the memory line up in the structure?
    By JHugh in forum C Programming
    Replies: 3
    Last Post: 08-01-2017, 06:13 AM
  3. Replies: 4
    Last Post: 07-19-2015, 05:51 PM
  4. I need your Help, structure in memory
    By Serj in forum C Programming
    Replies: 4
    Last Post: 12-09-2011, 12:15 PM
  5. Replies: 4
    Last Post: 04-25-2010, 10:57 AM

Tags for this Thread