Usage of sizeof
Defination
: sizeof
is a unary operation to get the storage size of a expression or data type (including primitive type, pointer or compound type), measured in the number of char-size unit.[1]
An example:
#include "stddef.h"
int arr[10];
size_t size = sizeof(arr);
// size is 40
Get the sizeof primitive data
char a = 10;
printf("size of char is %d", sizeof(a));
// size of char is 1
short a = 10;
printf("size of short is %d", sizeof(a));
// size of short is 2
int a = 10;
printf("size is int %d", sizeof(a));
// size of int is 4
Get the sizeof compound data
struct data {
int a;
int b;
};
struct data d = {1, 2};
printf("size of data is %d", sizeof(data));
// size of struct data_t is 8
printf("size of d is %d", sizeof(d));
// size of d is 8
printf("size of d.a is %d", sizeof(d.a));
// size of d.a is 4
Usually the processor can fetch world-aligned[2] object faster than it can fetch an object that straddles multiple words in memory.[3]
For more detailed, see Memory Alignment and Padding
struct data {
int a; // 4 bytes
int b; // 4 bytes
char c; // 1 bytes but padding 3 empty bytes
}
printf("size of struct data is %d", sizeof(struct data));
// size of struct data is 12
struct data {
int a;
struct data *b;
};
data d;
printf("size of struct data is %d", sizeof(struct data));
// size of struct data is 16
printf("size of d is %d", sizeof(d));
// size of d is 16
printf("size of d.b is %d", sizeof(d.b));
// size of d.b is 8
struct data
is 16
?
The int
requires 4 bytes and the pointer variable of the struct data
requires 4 bytes (on a 32-bits system). So the total size of structure is 8 bytes so far.
Because these members are not aligned with each other, the compiler adds padding bytes [4] between them to ensure that the pointer is properly aligned.
Get the sizeof pointer
char *a = "hello";
size_t length = sizeof(a);
// length is 8 (for 64bit system)
// length is 4 (for 32bit system)
When you holds a const array, you may use strlen to get the string size.
size_t length = strlen(a);
// length = 5
Get the sizeof array
char a[55] = "hello";
size_t length = sizeof(a);
// length is 55