9

Is there any way to speed up getting an array size in C?

Typing out sizeof(array)/sizeof(int) every time gets old. Do any C libraries have something like .length or is there some way I can define sizeof(array)/sizeof(int) as a shorter constant of some sort (possible also using dot notation)?

ubiquibacon
  • 10,451
  • 28
  • 109
  • 179
  • possible duplicate of [Is there a standard function in C that would return the length of an array? ](http://stackoverflow.com/questions/1598773/is-there-a-standard-function-in-c-that-would-return-the-length-of-an-array) – Michael Burr Dec 11 '10 at 06:39
  • C's treatment of arrays is the source of a lot of heartburn. – Rubens Mariuzzo Mar 22 '12 at 22:38

4 Answers4

12

You can use sizeof(array)/sizeof(*array) and make a macro.

#define length(array) (sizeof(array)/sizeof(*(array)))
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Šimon Tóth
  • 35,456
  • 20
  • 106
  • 151
12

All solutions in C boil down to a macro:

#define ARRAY_LENGTH(array) (sizeof((array))/sizeof((array)[0]))
MSN
  • 53,214
  • 7
  • 75
  • 105
3

You could always just write a macro to do it. Note that it won't work as a function, since you'd have to demote the array to a pointer to its first element, so it'd just return sizeof(int *) / sizeof(int).

#define INTSIZE(array) (sizeof(array) / (sizeof(int))

Or, more generally...

#define SIZE(array, type) (sizeof(array) / (sizeof(type))

Wow, downvotes. Okay, this will also work:

#define SIZE(array) (sizeof(array) / (sizeof((array)[0]))
nmichaels
  • 49,466
  • 12
  • 107
  • 135
  • To expand on Let_Me_Be's comment, you can write `sizeof arr / sizeof *arr` and not worry about type *at all* (although in the context of a macro it may be safer to write it as `(sizeof (arr) / sizeof *(arr)`). – John Bode Nov 29 '10 at 21:04
  • Actually using a separate type is kind of dangerous, but I have removed the downvote, since you edited the answer. – Šimon Tóth Nov 29 '10 at 23:10
2

The short answer is "no"; in C, there is no way to get the number of elements in an array based on the array expression alone. The sizeof trick is about as good as it gets, and its use is limited to expressions of array type. So the following won't work:

char *foo = malloc(1024);
size_t count = sizeof foo; 

count receives the number of bytes for the pointer type (4 on a typical desktop architecture), not in the allocated block.

char arr[100];
char *p = arr;
size_t count = sizeof p; 

Same as above.

void foo(char *arr)
{
  size_t count = sizeof arr; // same as above
  ...
}

void bar(void)
{
  char array[100];
  foo(array);
  ... 
}

Same as above.

If you need to know how many elements are in an array, you need to track that information separately.

C's treatment of arrays is the source of a lot of heartburn.

John Bode
  • 119,563
  • 19
  • 122
  • 198