-1
#include <stdio.h>
#pragma pack(1)

typedef struct 
{
  char name[10];
  int age;
  int class;
  char grade;
}stud_s;

int main(void)
{
  stud_s s1= {"john" ,10, 10, 'A'};
  printf("%ld \n",sizeof(stud_s));
  return 0;
}

In the above structure the name is reserved 10 bytes. And the name "john" is 4 bytes so when I use #pragma the size of structure should be 13. Instead the size resulted in 19 bytes. Could anyone have a look at my code? Any help would be appreciated.

user3770743
  • 59
  • 2
  • 2
  • 7
  • 1
    Because 10 + 4 + 4 + 1 = 19 (at least in my trip through academia). Structure size is settled at *compile* time; not *run* time. Packed or not makes no difference in that fact. – WhozCraig Jul 04 '14 at 02:54
  • @WhozCraig: The confusion is because they think that because `"john"` is only 4 bytes (which it isn't), then they would save 6 bytes in `stud_s::name`. Thus `19 - 6 = 13` as suggested in the question. – Bill Lynch Jul 04 '14 at 02:55
  • In that case what am I supposed to do get the size of the structure as 13. – user3770743 Jul 04 '14 at 02:56
  • 1
    @user3770743 Nothing. You can't. Unless you invent your own dynamic serialization buffer (or use someone else's, and either way, no small task) you're limited to compile-time sizing, packed or not. What is the *real* problem? Why does that structure with the name "John" need to be 13 bytes *exactly* ? – WhozCraig Jul 04 '14 at 02:59
  • http://stackoverflow.com/questions/11770451/what-is-the-meaning-of-attribute-packed-aligned4/11772340#11772340 – Jeyaram Jul 04 '14 at 03:51

2 Answers2

0

You're slightly confused as to what pragma pack does. It doesn't care about a particular instantiation, but about the padding in between elements.

Let's look at a simpler object:

struct obj {
    uint64_t x;
    uint32_t y;
};

Normally, this object will take 16 bytes. If you use pragma pack(1), it will only use 12 bytes.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
0

In C it is not possible to define a structure containing an array whose size depends on the contents of the initializer. You could use a C99 flexible array member, but then you would have to allocate the structure using malloc.

In C++ you could perhaps do something clever with templates and inheritance, but then the name member would not be part of the base type, which would be inconvenient.

In neither case does #pragma pack help. That common extension only removes padding in between structure fields.

zwol
  • 135,547
  • 38
  • 252
  • 361