I created an union and I put different types of array inside of it. I printed outputs in an order and I really didn’t understand some points.
1) Why is my char array’s length always 8 even the content is different? There is only “hello” inside of it. And why does the output is “Cats rock!” when I try to print for second time. I didn’t put anything like that inside array.
2)Again length problem. Lenghts of all my arrays are 8 even the length of union. Why?
3) My last question is why double number’s value changed when I try to print for the second time.
I’m posting you my code and out put that I get. Sorry about long post, but I’m really confused.
char: hello, 8
double: 5.557111111111111, 8
int: 1937006915 1668248096 8555, 8
char: Cats rock!
double: 0.000000000000000
int: 1937006915 1668248096 8555
size of union: 8
my code
#define NUM1 5.557111111111111
#define NUM2 1937006915
#define NUM3 1668248096
#define NUM4 8555
#include <stdio.h>
/*created an union*/
typedef union {
char * array1;
double num;
int * array2;
} myunion;
int main(int argc, char ** argv)
{
/* declaring union variable */
myunion uni;
/* creating my string */
char strarray[] = "hello";
/* declare an int array*/
int numarray[] = { NUM2, NUM3, NUM4 };
/* assign the string to the char pointer in the union */
uni.array1 = strarray;
/* print the union and the sizeof of the pointer */
printf("char: %s, %zu\n", uni.array1,sizeof(uni.array1));
/* assign NUM1 to the double part of union */
uni.num = NUM1;
/* print the double and its sizeof */
printf("double: %10.15f, %zu\n", uni.num, sizeof(uni.num));
/* assign array2 of union to the numarray */
uni.array2 = numarray;
/* print the values and the sizeof */
printf("int: %d %d %d, %zu\n", uni.array2[0], uni.array2[1], uni.array2[2], sizeof(uni.array2));
/* print the char array, double and int array */
printf("\nchar: %s \ndouble: %10.15f \nint: %d %d %d\n",uni.array1, uni.num, uni.array2[0], uni.array2[1], uni.array2[2]);
/* print the size of the union */
printf("size of union: %zu\n", sizeof(uni));
return 0;
}
sizeof(uni.array1)is always 8 on 64-bit platforms and 4 on 32-bit ones because it is taking the size of a pointer, not knowing how much data you believe might be behind that pointer. Similar for the arrays. C pointers which you make point to an array are “dumb” and do not understand how large the array is–you need to pass that information around separately.This covers your question parts 1 and 2. We like to answer specific questions here, so feel free to move your third inquiry to a separate post.