sri*_*iks 21 c c++ arrays function-prototypes
其中一个面试问题让我"编写一个C函数的原型,它采用了16个整数的数组",我想知道它可能是什么?也许像这样的函数声明:
void foo(int a[], int len);
Run Code Online (Sandbox Code Playgroud)
或者是其他东西?
那么如果语言是C++呢?
Jon*_*ler 44
在C中,这需要一个指向16个整数数组的指针:
void special_case(int (*array)[16]);
Run Code Online (Sandbox Code Playgroud)
它将被称为:
int array[16];
special_case(&array);
Run Code Online (Sandbox Code Playgroud)
在C++中,您也可以使用对数组的引用,如Nawaz的回答所示.(问题在标题中询问C,最初只在标签中提到了C++.)
任何使用以下变体的版本:
void alternative(int array[16]);
Run Code Online (Sandbox Code Playgroud)
最终相当于:
void alternative(int *array);
Run Code Online (Sandbox Code Playgroud)
在实践中,它将接受任何大小的数组.
问题是 - special_case()确实阻止了不同大小的数组传递.答案是'是'.
void special_case(int (*array)[16]);
void anon(void)
{
int array16[16];
int array18[18];
special_case(&array16);
special_case(&array18);
}
Run Code Online (Sandbox Code Playgroud)
编译器(MacOS X 10.6.6上的GCC 4.5.2,发生时)抱怨(警告):
$ 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]’
$
Run Code Online (Sandbox Code Playgroud)
更改为GCC 4.2.1 - 由Apple提供 - 并且警告是:
$ /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
$
Run Code Online (Sandbox Code Playgroud)
4.5.2中的警告更好,但实质内容相同.
Chr*_*oph 11
有几种方法可以声明固定大小的数组参数:
void foo(int values[16]);
Run Code Online (Sandbox Code Playgroud)
接受任何指针指向int,但数组大小作为文档
void foo(int (*values)[16]);
Run Code Online (Sandbox Code Playgroud)
接受指向具有正好16个元素的数组的指针
void foo(int values[static 16]);
Run Code Online (Sandbox Code Playgroud)
接受指向具有至少16个元素的数组的第一个元素的指针
struct bar { int values[16]; };
void foo(struct bar bar);
Run Code Online (Sandbox Code Playgroud)
接受一个装有16个元素的数组的结构,按值传递它们.
&在C++中是必要的:
void foo(int (&a)[16]); // & is necessary. (in C++)
Run Code Online (Sandbox Code Playgroud)
注意:&是必要的,否则你可以传递任何大小的数组!
对于C:
void foo(int (*a)[16]) //one way
{
}
typedef int (*IntArr16)[16]; //other way
void bar(IntArr16 a)
{
}
int main(void)
{
int a[16];
foo(&a); //call like this - otherwise you'll get warning!
bar(&a); //call like this - otherwise you'll get warning!
return 0;
}
Run Code Online (Sandbox Code Playgroud)
演示:http://www.ideone.com/fWva6
| 归档时间: |
|
| 查看次数: |
13869 次 |
| 最近记录: |