Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common array length macro for C? [duplicate]

I've seen several macros for array length floating around:

From this question:

  • #define length(array) (sizeof(array)/sizeof(*(array)))
  • #define ARRAY_LENGTH(array) (sizeof((array))/sizeof((array)[0]))
  • #define SIZE(array, type) (sizeof(array) / (sizeof(type))

And Visual Studio's _countof:

#define _countof(_Array) (sizeof(_Array) / sizeof(_Array[0])) 

What I'd like to know is:

  1. What's the difference between those using array[0] and *array?
  2. Why should either be preferred?
  3. Do they differ in C++?
like image 264
Matt Joiner Avatar asked Dec 11 '10 06:12

Matt Joiner


People also ask

How do I determine the length of my 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.

Can array size be increased in C?

Arrays are static so you won't be able to change it's size. You'll need to create the linked list data structure. The list can grow and shrink on demand.

What is ## in macro in C?

Token-pasting operator (##) The '##' pre-processing operator performs token pasting. When a macro is expanded, the two tokens on either side of each '##' operator are combined into a single token, which then replaces the '##' and the two original tokens in the macro expansion.

How do you find the size of an array?

We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);


1 Answers

Here's a better C version (from Google's Chromium project):

#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x]))))) 

It improves on the array[0] or *array version by using 0[array], which is equivalent to array[0] on plain arrays, but will fail to compile if array happens to be a C++ type that overloads operator[]().

The division causes a divide-by-zero operation (that should be caught at compile time since it's a compile-time constant expression) for many (but not all) situations where a pointer is passed as the array parameter.

See Is there a standard function in C that would return the length of an array? for more details.

There's a better option for C++ code. See Compile time sizeof_array without using a macro for details.

like image 142
Michael Burr Avatar answered Oct 08 '22 19:10

Michael Burr