如何找到未定义大小的数组的长度数组、长度、大小、未定义

2023-09-11 05:33:45 作者:丿灬哥的范儿丶

考虑由它定义的长度的阵列的配置:

Given an array with a length defined by it's configuration:

int a[] = {1,2,3,4,5,6,......n}; // Size of the array may change adding/deleting elements

它怎么可能知道在运行时数组的长度,例如循环的所有数组元素,而无需手动设置循环限制为n?

How it's possible to know at runtime the array length, for example to loop on all the array elements without having to manually set the loop limit to n?

int a[] = {1,2,3,4,5};
float b[] = {1.2, 0.1, 3.2};

printf("Array a size is %d\n", dim(a));
printf("Array b size is %d\n", dim(b));

你是如何定义暗淡()

推荐答案

假设它在全球或局部范围和定义的实际阵列不会一个参数的函数,你可以这样做:

Assuming it's an actual array defined in either global or local scope and NOT a parameter to a function, you would do this:

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

第一部分,的sizeof(一),给你以字节为单位的总规模,而第二部分,的sizeof(A [0] ),为您提供了一个成员的字节数。信号划分为您提供元件的数量,而不管阵列的类型的

The first part, sizeof(a), gives you the total size in bytes, and the second part, sizeof(a[0]), gives you the size in bytes of one member. Dividing them gives you the number of elements, regardless of the type of the array.

它不会工作,如果阵列是一个函数参数的原因是因为数组衰变到一个指向第一个元素传递给一个函数的时候。所以这样的:

The reason it won't work if the array is a function parameter is because arrays decay to a pointer to the first element when passed to a function. So this:

void func(int a[]);

是相同的:

void func(int *a);

因此​​,使用前pression上面的函数参数不会产生预期的结果。

So using the expression above on a function parameter will not yield the expected result.

 
精彩推荐
图片推荐