如何确定C语言中数组的大小?

也就是说,数组可以容纳多少元素?


当前回答

您可以使用sizeof操作符,但它不适用于函数,因为它将接受指针的引用。 您可以执行以下操作来查找数组的长度:

len = sizeof(arr)/sizeof(arr[0])

代码最初在这里找到:

查找数组中元素个数的C程序

其他回答

最简单的答案:

#include <stdio.h>

int main(void) {

    int a[] = {2,3,4,5,4,5,6,78,9,91,435,4,5,76,7,34}; // For example only
    int size;

    size = sizeof(a)/sizeof(a[0]); // Method

    printf("size = %d", size);
    return 0;
}

要知道在代码中显式声明并由其变量引用的固定数组的大小,可以使用sizeof,例如:

int a[10];
int len = sizeof(a)/sizeof(int);

但这通常是没有用的,因为你已经知道答案了。

但如果你有一个指针,你不能使用sizeof,这是一个原则问题。

但是…由于数组是作为线性内存提供给用户的,如果您知道最后一个元素地址,并且如果您知道类型的大小,那么您就可以计算它有多少个元素。例如:

#include <stdio.h>

int main(){
    int a[10];
    printf("%d\n", sizeof(a)/sizeof(int));
    int *first = a;
    int *last = &(a[9]);
    printf("%d\n", (last-first) + 1);
}

输出:

10
10

另外,如果你不能利用编译时,你可以:

#include <stdio.h>

int main(){
    int a[10];
    printf("%d\n", sizeof(a)/sizeof(int));
    void *first = a;
    void *last = &(a[9]);
    printf("%d\n", (last-first)/sizeof(int) + 1);
}

“你这是搬起石头砸自己的脚。”

C 'native'数组不存储它们的大小。因此,建议将数组的长度保存在单独的变量/const中,并在传递数组时传递它,即:

#define MY_ARRAY_LENGTH   15
int myArray[MY_ARRAY_LENGTH];

如果你正在编写c++,无论如何你都应该避免本机数组(除非你不能,在这种情况下,小心脚下)。如果你正在编写c++,请使用STL的“vector”容器。“与数组相比,它们提供了几乎相同的性能”,而且它们更有用!

// vector is a template, the <int> means it is a vector of ints
vector<int> numbers;  

// push_back() puts a new value at the end (or back) of the vector
for (int i = 0; i < 10; i++)
    numbers.push_back(i);

// Determine the size of the array
cout << numbers.size();

看到的: http://www.cplusplus.com/reference/stl/vector/

对于预定义数组:

 int a[] = {1, 2, 3, 4, 5, 6};

计算数组中的元素数量:

 element _count = sizeof(a) / sizeof(a[0]);
sizeof(array) / sizeof(array[0])