0

Is someone familiar with C language specification and can explain the idea of structures in C? I always thought that array in C is always a pointer (i.e. 4 bytes of data in 32bit systems) but in context of structures there is a slight difference.

When you define structure with a constant size array (e.g. int ns[5]) the size of the structure is 5*sizeof(int) = 20 bytes. I predicted it to be just 4 bytes. When you pass the structures by the value you create a whole new structure along with data in that array.

From the other hand when you have a structure with a dynamic size array (e.g. int *ns) the size is just sizeof(int *) = 4 bytes as predicted.

You can see and try the source code here: http://ideone.com/8gQhZT where i print:

printf("Size of static = %d and size of the dynamic = %d", sizeof(a), sizeof(b));

for static and dynamic structure.

I would like to know if it is consistent with C language specification and why is solved that way.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • 1
    It is probably not a duplicate - i'm looking for some reference to specification and explanation in that context. –  Jan 24 '15 at 02:52
  • There is no difference "in the context of structures" ; variables in a structure behave just the same as variables not in a structure. (exception: structures may not contain VLAs but may contain Flexible Array Member). – M.M Jan 24 '15 at 03:06

1 Answers1

0

for the declaration

int a[5];

here you are declaring an array of 5 int

so the sizeof(a) == sizeof(int)*5

for

int *a;

here you are declaring a pointer (pointing to a case of type int) which holds an address of memory so for 32 bits architecture the address can be written in 32 bits but in other systems with 64 bits architecture the address of memory can be written in only 48 bits mostly because it is enough sufficient

that's why you get in this case for sizeof(a) the value 4 which means that your system stores addresses in memory with 32 bits