如何将数组传递到函数中并保留有关其长度的信息,而不单独传递长度?
[ self 问答 - 下面的答案比我的更好]
最佳答案
在 C 中,数组不能完全传递给函数,因此这是不可能的。当您传递数组名称时,它会衰减为指向第一个元素的指针。使用 sizeof 运算符不会以任何方式帮助您,因为它会为您提供指针的大小。
要么将数组的大小传递给函数,要么在数组末尾使用哨兵值。
#include <stdio.h>
int size(int *a)
{
int count = 0;
while(*a++ != -1)
count++;
return count + 1;
}
int main(void)
{
signed int a[] = { 3, 5, 7, 9, 10, -1};
printf("size of array is: %d\n", size(a));
}
关于c - 获取传递给 C 函数的数组长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22403232/