Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ the meaning of getting size of a array

Tags:

c++

arrays

Here is a macro for getting array size

#define array_size(array) \
(sizeof( array ) / (sizeof( array[0] ) * (sizeof( array ) != sizeof(void*) || sizeof( array[0] ) <= sizeof(void*)))

I think normally (sizeof( array ) / (sizeof( array[0] )) is good enough to get the size of the array.

I guess the part

(sizeof( array[0] ) * (sizeof( array ) != sizeof(void*) || sizeof( array[0] ) <= sizeof(void*)) 

is to avoid the whole thing divided by zero, anyone could help to explain?

Thanks in advance.

Cheers,

like image 357
r0n9 Avatar asked Apr 25 '13 12:04

r0n9


People also ask

How get the size of an array in C?

To determine the size of your array in bytes, you can use the sizeof operator: int a[17]; size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element.

What does size of array mean?

Array size. The size of an array is the product of the lengths of all its dimensions. It represents the total number of elements currently contained in the array. For example, the following example declares a 2-dimensional array with four elements in each dimension.

What does array size mean in C?

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows − type arrayName [ arraySize ]; This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type.


1 Answers

Multiplying sizeof array[0] in the divisor by

(sizeof( array ) != sizeof(void*) || sizeof( array[0] ) <= sizeof(void*))

makes the divisor zero if

sizeof array == sizeof(void*)

and

sizeof array[0] > sizeof(void*)

In those cases, you get a division by zero during the compilation, which would cause the compilation to fail.

These checks are an attempt to detect arguments that are pointers (be they the result of array-to-pointer conversion or not), since one can't know how large an "array" a pointer points to by using that quotient.

It fails if other pointer types have different sizes than void*, and it doesn't detect pointers to things that are not larger than void*s. It probably does more harm than good by lulling the author in a false sense of security.

like image 63
Daniel Fischer Avatar answered Sep 29 '22 12:09

Daniel Fischer