函數頭中的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?

我想知道:是否有可能在傳遞到函數頭的變量中的某些內容中,或者它總是為空?

4 个解决方案

#1


10  

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]。

#2


2  

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])
{

}

#3


2  

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.

如果原始數組需要保持原樣,則可以在函數中創建和使用該數組的副本。

#4


0  

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. The two declarations are equivalent to these:

名稱arr衰減為指向int的指針。這兩個聲明等同於:

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. So this declaration at global scope does not define a pointer to int:

名稱不衰減的兩個位置在數組的定義中,並作為sizeof的參數。所以這個全局范圍的聲明沒有定義指向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;是一個錯誤(但不必診斷)。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/10/29/346f6a97155b8e0e7927d55c16600a30.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com