0

In below code. When I print individual char array size it prints correct value. But when I print whole struct size at a time it adds one byte more for each char array.

How can I control padding between elements in struct using #pragma in GNU C++ compiler? Can I set it to 0?

#include <iostream>
using namespace std;

typedef struct s1{
    char test[15];
    char t2[15];
}s1;

typedef struct s2{
    int message_id;
    int message_size;
}s2;

typedef struct s3{
    char test[15];
    char t2[15];
    int a;
}s3;

typedef struct s4{
    char test[15];
    int a;
}s4;


int main() {
    s4 st;
    cout<<sizeof(s1)<<endl;
    cout<<sizeof(s2)<<endl;
    cout<<sizeof(s3)<<endl;
    cout<<sizeof(s4)<<endl;
    cout<<sizeof(st.test)<<endl;
    return 0;
}

-----------------------OUTPUT--------------------

30
8
36
20
15

How can I control padding between struct elements?

Dharmesh
  • 943
  • 4
  • 15
  • 26
  • 2
    The compiler is adding padding to align with memory better. See the wikipedia page on [Data Structure Alignment](https://en.wikipedia.org/wiki/Data_structure_alignment) for more information. – clcto Mar 11 '15 at 17:11
  • 2
    \0 is only inserted at the end of c-string literals, if you declare an array of size 15, it will be 15 long. If the size is bigger than expected it's due to padding/alignment, not \0 (which again only makes sense with string literals, not arrays in general) – Borgleader Mar 11 '15 at 17:11
  • 1
    Most compilers allow you to prevent padding. In GCC you can use `__attribute__((packed))`. Note that this also prevents the compiler from the optimizations it could achieve with alignment/padding (like SSE). Packed structs can be useful, for instance when you're looking at a network buffer through as struct. – Alfred Bratterud Mar 11 '15 at 17:20

0 Answers0