如何确定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;
}

其他回答

执行概要:

int a[17];
size_t n = sizeof(a)/sizeof(a[0]);

完整的回答:

要确定数组的字节大小,可以使用sizeof 接线员:

int a[17];
size_t n = sizeof(a);

在我的电脑上,int是4字节长,所以n是68。

要确定数组中元素的数量,我们可以除法 数组的总大小乘以数组元素的大小。 你可以这样处理类型,像这样:

int a[17];
size_t n = sizeof(a) / sizeof(int);

并得到正确的答案(68 / 4 = 17)但如果类型 如果你忘记改变,你会有一个讨厌的bug sizeof(int)也是。

因此首选除数是sizeof(a[0])或等效的sizeof(*a),即数组第一个元素的大小。

int a[17];
size_t n = sizeof(a) / sizeof(a[0]);

另一个优点是您现在可以轻松地参数化 宏中的数组名,get:

#define NELEMS(x)  (sizeof(x) / sizeof((x)[0]))

int a[17];
size_t n = NELEMS(a);
sizeof(array) / sizeof(array[0])

最简单的答案:

#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;
}

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

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/

如果你正在处理没有作为参数接收的数组,sizeof方式是正确的方式。作为参数发送给函数的数组被视为指针,因此sizeof将返回指针的大小,而不是数组的大小。

因此,在函数内部,此方法不起作用。相反,始终传递一个额外的参数size_t size,指示数组中元素的数量。

测试:

#include <stdio.h>
#include <stdlib.h>

void printSizeOf(int intArray[]);
void printLength(int intArray[]);

int main(int argc, char* argv[])
{
    int array[] = { 0, 1, 2, 3, 4, 5, 6 };

    printf("sizeof of array: %d\n", (int) sizeof(array));
    printSizeOf(array);

    printf("Length of array: %d\n", (int)( sizeof(array) / sizeof(array[0]) ));
    printLength(array);
}

void printSizeOf(int intArray[])
{
    printf("sizeof of parameter: %d\n", (int) sizeof(intArray));
}

void printLength(int intArray[])
{
    printf("Length of parameter: %d\n", (int)( sizeof(intArray) / sizeof(intArray[0]) ));
}

输出(64位Linux操作系统):

sizeof of array: 28
sizeof of parameter: 8
Length of array: 7
Length of parameter: 2

输出(32位windows操作系统):

sizeof of array: 28
sizeof of parameter: 4
Length of array: 7
Length of parameter: 1