Advanced C topics – Part1

I just want to touch in this post some of the things which are generally considered to be advanced C topics. I am referring here to things like: differences between pointers and arrays, arrays passed as parameters and returned as value from functions, and pointers to functions.

Can we pass an array as a function parameter in C language? Isn’t quite strange when we see in C programs something like this:

void function (int a[], int n);

How can one pass an entire array as a parameter to a function? How many parameters does the corresponding function accept, two or many?
The answer is quite straightforward: you are passing in fact just an address as a parameter. This is a pointer to the first element of the array. It is the old discussion about different ways of how to refer to an array or to an element of it (if you define it like this int a[] you can refer to it like this int *a; and refer to its elements with *(a+2) – third element in the array; or you can refer like this a[2] – 3’rd element).
Please be aware when passing arrays not to overflow the stack. This is the danger that arrays passed as parameters may involve: compiler never knows how big the array will be, because it will replace the array declaration with a pointer so it will reserve space just for a pointer.

Actually when defining an array the compiler automatically generates a pointer to its first element, it is something like this:


void function (int &a[0], int n);

Read more of this post

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
sizeof(int)
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[];

Read more of this post