写原型为恰恰16整数数组功能 [英] Write the prototype for a function that takes an array of exactly 16 integers
问题描述
一个面试问题问我写的原型为一个C函数,它正好是16整数数组,我想知道这可能是什么?也许一个函数的声明是这样的:
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?
和怎么样,如果语言是C ++呢?
And what about if the language was C++ instead?
推荐答案
在C,这需要一个指向16整数数组:
In C, this requires a pointer to an array of 16 integers:
void special_case(int (*array)[16]);
这将与被称为:
int array[16];
special_case(&array);
在C ++中,你可以使用一个引用到一个数组,也如图的纳瓦兹答案。 (这个问题询问℃的称号,并原本只在标签中提到C ++)。
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]);
最后等于为:
void alternative(int *array);
这将接受阵列的任何尺寸,在实践中。
which will accept any size of array, in practice.
现在的问题是问 - 确实 special_case()
真的prevent被传递不同大小的数组。答案是是。
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);
}
编译器(GCC 4.5.2上的MacOS X 10.6.6,因为它发生)抱怨(警告):
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]’
$
切换到GCC 4.2.1 - 为苹果公司提供 - 和警告是:
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
$
在4.5.2警告较好,但实质是一样的。
The warning in 4.5.2 is better, but the substance is the same.
这篇关于写原型为恰恰16整数数组功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!