Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof() applied to structure and variable

Tags:

c

clang

consider the following snippet:

struct foo {
  int a;
  int b;
  int c;
};

struct foo f;
printf("%u, %u\n", sizeof(struct foo), sizeof(f));

The code returns the same values, but I was wondering if sizeof() applied to variable is correct or this is just coincidence?

Thanks.

like image 971
Mark Avatar asked Sep 09 '11 18:09

Mark


People also ask

Does sizeof work on variables?

The sizeof operator is the most common operator in C. It is a compile-time unary operator and used to compute the size of its operand. It returns the size of a variable. It can be applied to any data type, float type, pointer type variables.

Can you use sizeof on a struct?

The sizeof for a struct is not always equal to the sum of sizeof of each individual member. This is because of the padding added by the compiler to avoid alignment issues. Padding is only added when a structure member is followed by a member with a larger size or at the end of the structure.

What is the size of structure variable?

In 32 bit processor, it can access 4 bytes at a time which means word size is 4 bytes. Similarly in a 64 bit processor, it can access 8 bytes at a time which means word size is 8 bytes.

What is the relationship between the result of sizeof () for a structure variable and the sum of the sizeof () calls across the same structure's members?

The result of the sizeof operand applied to a structure object can be equal to the sum of sizeof applied to each member separately.


1 Answers

Both will and should indeed return the same value.

From MSDN:

The sizeof Operator
The sizeof operator gives the amount of storage, in bytes, required to store an object of the type of the operand. This operator allows you to avoid specifying machine-dependent data sizes in your programs.

sizeof unary-expression  
sizeof ( type-name )
like image 65
Alok Save Avatar answered Nov 26 '22 21:11

Alok Save