开发者

Is there any shortcut for array size / length in C?

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

Typing out sizeof(array)/sizeof(int) every time gets old. Do a开发者_开发问答ny 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)?


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

#define length(array) (sizeof(array)/sizeof(*(array)))


All solutions in C boil down to a macro:

#define ARRAY_LENGTH(array) (sizeof((array))/sizeof((array)[0]))


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]))


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜