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

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


当前回答

#define SIZE_OF_ARRAY(_array) (sizeof(_array) / sizeof(_array[0]))

其他回答

你可以使用&操作符。以下是源代码:

#include<stdio.h>
#include<stdlib.h>
int main(){

    int a[10];

    int *p; 

    printf("%p\n", (void *)a); 
    printf("%p\n", (void *)(&a+1));
    printf("---- diff----\n");
    printf("%zu\n", sizeof(a[0]));
    printf("The size of array a is %zu\n", ((char *)(&a+1)-(char *)a)/(sizeof(a[0])));


    return 0;
};

下面是示例输出

1549216672
1549216712
---- diff----
4
The size of array a is 10

对于多维数组,它稍微复杂一些。通常人们定义显式宏常量,即。

#define g_rgDialogRows   2
#define g_rgDialogCols   7

static char const* g_rgDialog[g_rgDialogRows][g_rgDialogCols] =
{
    { " ",  " ",    " ",    " 494", " 210", " Generic Sample Dialog", " " },
    { " 1", " 330", " 174", " 88",  " ",    " OK",        " " },
};

但是这些常量也可以在编译时用sizeof求值:

#define rows_of_array(name)       \
    (sizeof(name   ) / sizeof(name[0][0]) / columns_of_array(name))
#define columns_of_array(name)    \
    (sizeof(name[0]) / sizeof(name[0][0]))

static char* g_rgDialog[][7] = { /* ... */ };

assert(   rows_of_array(g_rgDialog) == 2);
assert(columns_of_array(g_rgDialog) == 7);

注意,这段代码可以在C和c++中运行。对于二维以上的数组,请使用

sizeof(name[0][0][0])
sizeof(name[0][0][0][0])

等等,无限。

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

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/

注意:正如M.M在评论中指出的那样,这可能会给你未定义的行为。

int a[10];
int size = (*(&a+1)-a);

要了解更多细节,请参见这里和这里。

sizeof函数返回数组在内存中使用的字节数。如果你想计算数组中的元素数量,你应该用数组的sizeof变量类型除以这个数字。让我们说int array[10];,如果变量类型integer在你的计算机是32位(或4字节),为了得到你的数组的大小,你应该做以下工作:

int array[10];
size_t sizeOfArray = sizeof(array)/sizeof(int);