-2

The sizeof a union is equal to the size of the largest member in it. But in the following union, the size is being shown to be 8 Bytes. Size of int and float is 4 Bytes. Why does it show 8 Bytes?

union data {
    int i;
    float f;
    char *str;
};
timrau
  • 22,578
  • 4
  • 51
  • 64
Sudha Sompura
  • 87
  • 1
  • 7

4 Answers4

6

sizeof(char *) is the size of the pointer. It's usually 4 for 32-bit machine, and 8 for 64-bit machine. Given your result, I take it you're on a 64-bit machine.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
Daniel Almeida
  • 372
  • 1
  • 14
6
#include <stdio.h>

union data_t {
  int i;
  float f;
  char *str;
};

int main()
{
  union data_t data;
  printf("%zu\n%zu\n%zu\n", sizeof (data.i), sizeof (data.f), sizeof (data.str));
  printf("\nsizeof(char*): %zu\nsizeof(char): %zu\n", sizeof(char *), sizeof(char));
}

Output:

$ ./a.out 
4
4
8

sizeof(char*): 8
sizeof(char): 1
klutt
  • 30,332
  • 17
  • 55
  • 95
3

Size of union = size of the largest data type used

The memory occupied by a union will be large enough to hold the largest member of the union. It doesn't matter what is currently in use. For example,

union Data 
 {
   int i;
   float f;
   char str[20];
 } data; 

Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. It means a single variable, i.e., same memory location, can be used to store multiple types of data. Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by a character string.

yash darak
  • 368
  • 4
  • 17
2

Try the code below on a Windows 64/Linux 64 and the result should be 8, on a 32 bit system should be 4.

int main(void)
{
    char * str;

    printf("%d\n",sizeof(str));

    return 0;

}
Sir Jo Black
  • 2,024
  • 2
  • 15
  • 22