简体   繁体   English

函数头中的C / C ++数组变量

[英]C/C++ array variable in function header

We can pass an array as a variable in a C/C++ function header, as in 我们可以将数组作为C / C ++函数头中的变量传递,如

int func(int arr[]) { ... }

I'm wondering: Is it ever possible that something goes inside the [] in a variable that's passed into the function header, or is it always empty? 我想知道:在传递到函数头的变量中,某些东西是否可能进入[] ,或者它总是为空?

For any (non-reference) type T , the function signatures R foo(T t[]) and R foo(T t[123]) (or any other number) are identical to R foo(T * t) , and arrays are passed by passing the address of the first element. 对于任何(非参考)类型T ,函数签名R foo(T t[])R foo(T t[123]) (或任何其他数字)与R foo(T * t)和数组相同通过传递第一个元素的地址传递。

Note that T may itself be an array type, such as T = U[10] . 注意, T本身可以是数组类型,例如T = U[10]

for a one-dimensional array, it will always be empty, the brackets are another way of writing: 对于一维数组,它将始终为空,括号是另一种写入方式:

int fun(int * arr)
{

}

As for a two-dimensional array, you need to specify how many elements each element itself holds 对于二维数组,您需要指定每个元素本身包含的元素数量

int fun(int arr[][3])
{

}

int func(int arr[]) { ... } is an invalid decleration of an array passed to a function. int func(int arr []){...}是传递给函数的数组的无效decleration。

An array name is a pointer variable. 数组名称是指针变量。 so it is enough that we just pass the array name (which itself is a pointer ) 所以我们只需传递数组名称(它本身就是一个指针)就足够了

int func(int *arr) { ... } will pass the starting address of the array to the function so that it can use the array. int func(int * arr){...}会将数组的起始地址传递给函数,以便它可以使用该数组。

if the original array needs to be kept intact, a copy of the array can be created & used within the function. 如果原始数组需要保持原样,则可以在函数内创建和使用该数组的副本。

The name of an array decays into a pointer to its first element in most contexts. 在大多数上下文中,数组的名称衰减为指向其第一个元素的指针 So when you write 所以当你写作

void f(int arr[]);
void g(int arr[42]);

the name arr decays into a pointer to int. 名称arr衰减为指向int的指针。 The two declarations are equivalent to these: 这两个声明等同于:

void f(int *arr);
void g(int *arr);

Two places where the name does not decay are in the definition of an array and as an argument to sizeof . 名称不会衰减的两个位置在数组的定义中,并作为sizeof的参数。 So this declaration at global scope does not define a pointer to int: 所以这个全局范围的声明没有定义指向int的指针:

int arr[];

I mention this particular one because it's an easy mistake to make and one that's hard to track down. 我提到这个特别之一,因为这是一个容易犯的错误,而且很难追查。 This defines an array, not a pointer, even though the number of elements is not specified. 这定义了一个数组,而不是一个指针,即使没有指定元素的数量。 It is an error (but one that doesn't have to be diagnosed) to refer to arr from another source file as int *arr; 这是一个错误(但一个没有被诊断)是指arr从另一个源文件为int *arr; .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM