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

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


当前回答

如果你知道数组的数据类型,你可以像这样使用:

int arr[] = {23, 12, 423, 43, 21, 43, 65, 76, 22};

int noofele = sizeof(arr)/sizeof(int);

或者如果你不知道数组的数据类型,你可以使用类似这样的东西:

noofele = sizeof(arr)/sizeof(arr[0]);

注意:只有当数组在运行时没有定义(如malloc)并且数组没有传递到函数中时,这个东西才有效。在这两种情况下,arr(数组名)都是指针。

其他回答

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

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

#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])

等等,无限。

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

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

代码最初在这里找到:

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

C中数组的大小:

int a[10];
size_t size_of_array = sizeof(a);      // Size of array a
int n = sizeof (a) / sizeof (a[0]);    // Number of elements in array a
size_t size_of_element = sizeof(a[0]); // Size of each element in array a                                          
                                       // Size of each element = size of type

对于预定义数组:

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

计算数组中的元素数量:

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