为什么将C数组传递给size时会衰减到指针 [英] Why does a C array decay to a pointer when passed with size
问题描述
我了解为什么数组在传递给函数时未指定其大小就衰减为指针,例如:
void测试(int array []);
为什么在传递尺寸时会这样做?例如.
void测试(int array [3]);
我在后一个函数签名下遇到 sizeof
时遇到了麻烦,这很令人沮丧,因为在编译时就清楚地知道了数组的长度.
无效测试(int *数组);无效测试(int array []);无效测试(int array [3]);
所有这些变体都是相同的.C仅允许您使用其他拼写,但即使最后显式标注了数组大小的最后一个变体也会衰减为指向第一个元素的指针.
也就是说,即使使用最后一个实现,您也可以使用任意大小的数组来调用该函数:
无效测试(char str [10]){}测试一下");//有效.测试(让我们再尝试一些");//仍然有效.
没有神奇的解决方案,处理该问题的最易读的方法是使用数组+大小创建 struct
或仅将大小作为附加参数传递给函数./p>
LE:请注意,此转换仅适用于数组的第一维.传递给函数时, int [3] [3]
会转换为 int(*)[3]
,而不是 int **
.
I understand why an array decays to a pointer when passed to a function without specifying its size, eg.:
void test(int array[]);
Why does it do so when passed with the size? eg.
void test(int array[3]);
I am having trouble with sizeof
under the latter function signature, which is frustrating as the array length is clearly known at compile time.
void test(int* array);
void test(int array[]);
void test(int array[3]);
All these variants are the same. C just lets you use alternative spellings but even the last variant explicitly annotated with an array size decays to a pointer to the first element.
That is, even with the last implementation you could call the function with an array of any size:
void test(char str[10]) { }
test("test"); // Works.
test("let's try something longer"); // Still works.
There is no magic solution, the most readable way to handle the problem is to either make a struct
with the array + the size or simply pass the size as an additional parameter to the function.
LE: Please note that this conversion only applies to the first dimension of an array. When passed to a function, an int[3][3]
gets converted to an int (*)[3]
, not int **
.
这篇关于为什么将C数组传递给size时会衰减到指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!