So in my code I have the following structs defined in a header file:
test.h:
#ifndef TEST
#define TEST
typedef struct struct1 {
uint8_t a;
uint16_t b;
uint16_t c;
} struct1;
typedef struct struct2 {
uint8_t a;
uint8_t b;
uint8_t c;
uint8_t d;
uint8_t e;
struct struct1 f;
} struct2;
void doStuff(struct struct2 * s);
#endif
When I declare a struct2 and call a function with a pointer to it, values assigned inside the function don't match the values read outside of that function
main.c:
#include <stdint.h>
#include <stdio.h>
#include "test2.h"
#include "test.h"
int main(){
struct struct2 s;
s.a=0;s.b=0;s.c=0;s.e=0;
printf("Main's s's size: %d\n", sizeof(s));
doStuff(&s);
}
test.c:
#include <stdint.h>
#include <stdio.h>
#include "test.h"
void doStuff(struct struct2 * s){
printf("doStuff's size: %d\n", sizeof(*s));
}
test2.h:
#pragma pack(1)
When printing their sizes, sizeof(*s) inside doStuff returns 12, whileas inside the main function sizeof(s) returns 10. When comparing the addresses of each of the internal values, s.a through s.e match inside and outside the function, s.f and s.f.a are one off, and s.f.b and s.f.c are two off.
Any idea what's going on here?
(note: Question has been closed as a duplicate of what I don't believe it is a duplicate of. The real problem stems from test2.h's use of '#pragma pack(1)'. Moving the #include of test2.h to after that of test.h makes it work as expected. To run above, 'gcc -o test test.c main.c', under GCC 4.4)