Write the prototype for a function that takes an array of exactly 16 integers

sriks picture sriks · Jan 17, 2011 · Viewed 15.3k times · Source

One of the interview questions asked me to "write the prototype for a C function that takes an array of exactly 16 integers" and I was wondering what it could be? Maybe a function declaration like this:

void foo(int a[], int len);

Or something else?

And what about if the language was C++ instead?

Answer

Jonathan Leffler picture Jonathan Leffler · Jan 17, 2011

In C, this requires a pointer to an array of 16 integers:

void special_case(int (*array)[16]);

It would be called with:

int array[16];
special_case(&array);

In C++, you can use a reference to an array, too, as shown in Nawaz's answer. (The question asks for C in the title, and originally only mentioned C++ in the tags.)


Any version that uses some variant of:

void alternative(int array[16]);

ends up being equivalent to:

void alternative(int *array);

which will accept any size of array, in practice.


The question is asked - does special_case() really prevent a different size of array from being passed. The answer is 'Yes'.

void special_case(int (*array)[16]);

void anon(void)
{

    int array16[16];
    int array18[18];
    special_case(&array16);
    special_case(&array18);
}

The compiler (GCC 4.5.2 on MacOS X 10.6.6, as it happens) complains (warns):

$ gcc -c xx.c
xx.c: In function ‘anon’:
xx.c:9:5: warning: passing argument 1 of ‘special_case’ from incompatible pointer type
xx.c:1:6: note: expected ‘int (*)[16]’ but argument is of type ‘int (*)[18]’
$

Change to GCC 4.2.1 - as provided by Apple - and the warning is:

$ /usr/bin/gcc -c xx.c
xx.c: In function ‘anon’:
xx.c:9: warning: passing argument 1 of ‘special_case’ from incompatible pointer type
$

The warning in 4.5.2 is better, but the substance is the same.