sizeof() operator – not a trivial thing

sizeof() operator … Remember it?
That one mostly used when dynamically allocating memory:

int *pointer; /*pointer to type int, used to reference our allocated data*/
pointer = malloc(sizeof(int) * 10);

Some things about it:

– it returns the size in bytes of any primitive or user-defined variable
– it always returns something positive, as it is defined it returns an unsigned size_t type
– if a type is used like in this example
its argument needs to be parenthesized
-if just variable’s name is used parenthesis can be omitted

char c;
sizeof c
– in the C standards preceding C99 it was a compile-time operator, meaning that it calculated only sizes defined at compilation, it could not calculate something like this
char c[];

– after C99 it can calculate the size of such run-time variable
– in case if such un-sized array is an element of a structure, sizeof() operator returns the size of that structure excluding the array

An important thing which I was not aware until now is that sizeof can depend on data alignment within certain structures or classes. If you have a structure such as this one:

struct A{
char c;
int i;

sizeof (struct A) – can return 8 bytes, because most compilers align the data on word boundaries. The value of char c is stored on the next word due to the fact that the compiler may be optimized for the processor that runs on (processors, depending on their data bus width, can fetch faster data which has this particular width than data which is smaller)

Coming back to the dynamic array that I’ve just outlined above, there is another issue to discuss. One must pay attention to the way sizeof() calculates array’s sizes.

int array[]={1,4,5,7};
sizeof (array);
// depends on the compiler
// in some it will not return 4*ints but
// it will actually calculate the size of an int *

As you may already know this is the reason that arrays can be passed as arguments or parameters to functions: it is actually the pointer at the beginning of the array passed.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: