数组的长度计数异常 [英] Array length counting anomaly
问题描述
该计数未返回predictable结果。有时候,他们是对的。有时候完全不可思议。谁能告诉我什么是错?
的#include<&stdio.h中GT;
INT LEN(INT []);INT主(INT ARGC,为const char * argv的[])
{
诠释一个[] = {1,2,3,4,5};
为int * i为一个;
的printf(长度为%d,(LEN(I)));
返回0;
}INT LEN(INT *一){
诠释计数= 0;
对于(; * A ='\\ 0';!一++){
算上++;
}
返回计数;
}
我觉得你的C字符串(字符
的阵列)等阵列之间的混淆。它是C字符串终止与空字符('\\ 0'
),但不是所有的数组(甚至字符$ C $公约C>数组)终止这种方式。
的一般约定是要么存储数组的长度的地方,或在数组的结尾使用一个哨兵值。这个值应该是一个不上去阵内 - 例如'\\ 0'
的字符串或 1
正整数数组。
另外,如果你知道 A
是一个int数组(而不是指向一个int数组),那么你可以使用:
为size_t长度= sizeof的(A)/ sizeof的(A [0]);
所以,你可以这样做:
int类型的[] = {1,2,3,4,5};
为size_t长度= sizeof的(一)/的sizeof(一个[0]);//在这种情况下,的sizeof(一个[0])
//相同的sizeof(int)的,因为它是一个int数组。
但你不能做的:
为int * A =的malloc(sizeof的(INT)* 10);
为size_t长度= sizeof的(一)/的sizeof(一个[0]); // WRONG!
这是最后一个例子可以编译,但答案是错误的,因为你得到一个指针的大小数组,而不是数组的大小。
请注意,您也不能使用该的sizeof
读取的被传递给函数的数组的大小。这不要紧,你是否声明你的函数 LEN(INT * A)
或 LEN(int类型的[])
- A
将是一个指针,因为编译器在功能参数转换阵列是指向自己的第一个元素
The count is returning unpredictable results. Sometimes they are right. Sometimes totally weird. Anyone can tell me what is wrong?
#include <stdio.h>
int len(int[]);
int main (int argc, const char * argv[])
{
int a[]={1,2,3,4,5,6,7,8};
int* i = a;
printf("length is %d",(len(i)));
return 0;
}
int len(int* a){
int count = 0;
for (; *a!='\0'; a++) {
count++;
}
return count;
}
I think you're confused between C strings (arrays of char
) and other arrays. It's a convention that C strings are terminated with a null character ('\0'
), but not all arrays (even char
arrays) are terminated this way.
The general convention is to either store the length of an array somewhere, or to use a sentinel value at the end of the array. This value should be one that won't come up inside the array - eg '\0'
in strings, or -1
in an array of positive ints.
Also, if you know that a
is an int array (and not a pointer to an int array), then you can use:
size_t length = sizeof(a) / sizeof(a[0]);
So you could do:
int a[] = {1,2,3,4,5,6,7,8};
size_t length = sizeof(a) / sizeof(a[0]);
// In this case, sizeof(a[0])
// is the same as sizeof(int), because it's an int array.
But you can't do:
int *a = malloc(sizeof(int) * 10);
size_t length = sizeof(a) / sizeof(a[0]); // WRONG!
That last example will compile, but the answer will be wrong, because you're getting the size of a pointer to the array rather than the size of the array.
Note that you also can't use this sizeof
to read the size of an array that's been passed into a function. It doesn't matter whether you declare your function len(int *a)
or len(int a[])
- a
will be a pointer, because the compiler converts arrays in function arguments to be a pointer to their first element.
这篇关于数组的长度计数异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!