【发布时间】:2015-10-05 10:32:10
【问题描述】:
我需要找到一个数组的长度,如果不使用sizeof 函数,我将如何做到这一点。
如果
Array 1 = [0 1 2 3 4 5 6]
这个数组的大小是7。
【问题讨论】:
-
sizeof不是函数,而是运算符。 -
这不是 C 语法。
我需要找到一个数组的长度,如果不使用sizeof 函数,我将如何做到这一点。
如果
Array 1 = [0 1 2 3 4 5 6]
这个数组的大小是7。
【问题讨论】:
sizeof 不是函数,而是运算符。
如果您不能使用sizeof(请告诉我们原因),您可以使用循环和标记(-1 或数组中不能使用的某个数字):
int arr[] = {0, 1, 2, 3, 4, 5, 6, -1};
int count = 0;
while (arr[count] != -1) count++;
【讨论】:
!= -1。
sizeof 是一个运算符,而不是一个函数。如果这对您的问题产生影响。
(&Array_1)[1] 不是 &Array_1[1] 。那会有所作为。
许多高级编程语言在创建数组后会保存其长度。
/* e.g. Java */
int[] foo = new int[10];
assert(foo.length == 10);
但是数组的长度并没有保存在 C 中!这很有用,因为您可以决定如何保存与优化相关的长度。您基本上有三种可能来获取/保存长度:
用某个值标记数组的末尾(即\0用于字符串)
char foo[] = "bar";
/* foo has length 4(sic!) as '\0' is automatically added to the end*/
int i = 0;
while(foo[i] != '\0'){
printf("%c",foo[i]);
i++;
}
将数组的长度保存在变量中
int foo[] = {1,2,3,4};
int length = 4;
for(int i = 0; i < length;i++){
printf("%i, ",foo[i]);
}
使用 sizeof (警告:sizeof (大部分)是在编译时计算的,它的使用受到限制。您只能在创建数组的函数中使用 sizeof。当您将数组传递给函数时,您只能传递指向第一个元素的指针。因此,您可以循环遍历此数组,因为您知道必须使用什么偏移量(其元素的类型),但除非您还传递了长度或添加了一个标记值,否则您不知道它有多大)
/* ok */
int foo[] = {1,2,3,4};
for(int i = 0; i < sizeof(foo)/sizeof(int);i++){
printf("%i, ",foo[i]);
}
/* not ok */
void foo(int bar[]);
void foo(int bar[]){
for(int i = 0; i < sizeof(bar)/sizeof(int);i++){
printf("%i, ",bar[i]);
}
}
int main()
{
int arr[] = {1,2,3,4};
foo(arr);
return 0;
}
【讨论】: