So here is the problem:
I need to know how big is union (or something like that im new to C, and if i would like to know how to learn more of C i would be greatful)
Union should give me back hmm 20?
It gives me back 24 and i need an explenation.
#include <stdio.h>
#include <stdlib.h>
union Zadanie {
int calkowita;
char znak[20];
double rzeczywista;
}ZadanieU;
typedef struct {
int calkowita;
char znak[20];
double rzeczywista;
}ZadanieS;
int main()
{
ZadanieS z1 = {2,"Borys",3.5};
printf("%d,\n %s,\n%0.1f \n\n", z1.calkowita,z1.znak,z1.rzeczywista);
printf("Rozmiar unii: %d\n", sizeof(ZadanieU));
printf("Rozmiar Struktury: %d\n\n", sizeof(ZadanieS));
printf("Rozmiar unii Calkowitej:%d \n", sizeof(ZadanieU.calkowita));
printf("Rozmiar Struktury Calkowitej: %d\n\n", sizeof(z1.calkowita));
printf("Rozmiar unii Char:%d \n", sizeof(ZadanieU.znak));
printf("Rozmiar Struktury Char: %d\n\n", sizeof(z1.znak));
printf("Rozmiar unii Rzeczywistej:%d \n", sizeof(ZadanieU.rzeczywista));
printf("Rozmiar Struktury Rzeczywistej: %d\n\n", sizeof(z1.rzeczywista));
return 0;
}
sizeof(ZadanieU)
will tell you the difference between the addresses of two consecutive instances of that union in an array of that type.
On some architectures, double
values are aligned on 8-byte boundaries, and the union contains a double so it will be aligned on an 8-byte boundary too.
The difference between consecutive union addresses would therefore be 24.