Tuesday, 10 April 2012

Sizeof

So, this is the first of hopefully many mini-guides on how to do cool stuff in C...

You might usually use sizeof like this:

int *a = malloc(sizeof(int));

But a for many little known fact about C is that sizeof will get the size of the resulting type the of the expression given as the argument. This means that this line will do the same thing as the previous line:

int *a = malloc(sizeof(*a));

Since the expression *a will result in an int, the size of that expression is an int.

I went too long as a C-programmer without knowing this little fact.

No comments:

Post a Comment