union
{
int a;
char b;
char c[10];
}u1;

void main()
{
int l=sizeof(u1);
printf("%d",l);
getch();
}

This gives the output as 10, shouldnt it be 2 + 1 + 10 == 13 ???

Can some1 explain ?

Well, the size in memory is mostly dependent on the compiler. That asides, the size of c[10] would not be the size in memory of 10 char data types, but rather the size of a char pointer.

LevyDee is right IF the array had been sent to another function. In the function it was declared in, it will have size 10.

Tubby, the union has ONLY a size big enough for the largest member. THE largest member, not the SUM of all the members. That would be true for a struct, though. (along with some padding which would depend on your compiler, as LevyDee mentioned).

adak and levy dee, thanks a lot. ok union takes the size of the biggest member .. Will remember that ..
i have 1 more doubt. How does this give 3, shouldnt it give 3*sizeof(int) cuz its an integer array.

#include<stdio.h>
#include<conio.h>

int main()
{
 char arr[] = {1, 2, 3};
 char *p = arr;
 printf(" %d ", sizeof(arr));
 getchar();
 return 0;
}

Edited 5 Years Ago by tubby123: n/a

How does this give 3, shouldnt it give 3*sizeof(int) cuz its an integer array.

But it's not an int array, it's a char array.

Tubby, you have three digits in your array. It's not a string, because it has no end of string char at the end of it, and it's not three numbers, because the type of the array is declared to be char.

It's just the digit '1', and then the digit '2', and then the digit '3'.

And that's all it is, right now. Without quote marks in there, it may not compile, as is.

It's just the digit '1', and then the digit '2', and then the digit '3'.

This statement is either confused or misleading. The lack of single quotes means those initializers are not character literals, but the low end of character set typically doesn't include printable characters, so it's harder to say what the actual values are. Using ASCII as a base, we can say that 1, 2, and 3 are the control characters SOH, STX, and ETX, respectively. But they're most certainly not equivalent to the characters '1', '2', and '3', which (still assuming ASCII) have the values of 49, 50, and 51.

Without quote marks in there, it may not compile, as is.

Using a string literal to initialize an array of char is the exception (one provided for convenience), not the rule. The rule is using an initialization list as in tubby's code. So it's required to compile (assuming the rest of the code is equally correct).

Thanks, Narue! I wasn't even thinking about the possibility that Tubby meant to initialize the char array with the very low end of the character set (card suit icons and all that).

It's too late to edit my post, but Tubby, this is you warning - disregard my post above.

This article has been dead for over six months. Start a new discussion instead.