Need a suggestion for sizing an array in C in an efficient way

In java, java script and other languages ​​there are array.length functions available for knowing the length of the array for looping and other needs. And in C programming, I use

sizeof()    

to determine the size of the array or the length of the array, following the procedure:

  int array [] ={12, 3, 4, 6};

  for (int i = 0; i < (sizeof(array)/sizeof(int)); i++) {
 // do sometings
}

I want to know,

  sizeof(array)/sizeof(int)

effective for finding array size? Or, if other effective ways are available, please suggest me.

+3
source share
3 answers

It is extremely efficient because it is a construct that leads to a compile-time constant (except for VLAs C99, see below). You can use:

sizeof(array)/sizeof(array[0])

. , (, ).

: VLA C99, :

- , ; , . (6.5.3.4/2)

VLA ( ), VLA . VLA . :

#include <stdio.h>

#define countof_array(arr)  (sizeof(arr)/sizeof(arr[0]))

int vlaSize(void)
{
  return 8;
}

int main(void)
{
   int fixed_array[9] = { 1,2,3,4,5,6,7,8,9 };
   int vla_array[vlaSize()];

   printf("Fixed array: size = %zu bytes, count = %zu elements\n", 
           sizeof(fixed_array), countof_array(fixed_array));
   printf("VLA array:   size = %zu bytes, count = %zu elements\n", 
           sizeof(vla_array), countof_array(vla_array));

   return 0;
}

:

$ gcc -Wall -std=c99 so-misc.c
$ ./a.out
Fixed array: size = 36 bytes, count = 9 elements
VLA array:   size = 32 bytes, count = 8 elements

, :

. , countof_array VLA [...]

, , , . .

, - , VLA , VLA. , VLA, - .

+4

sizeof - , , , . "" sizeof , , .

, , , .

0

sizeof ( ).

C99 (Vlas).

C ( C99) (VLA), (FAM). sizeof , - std::vector::size() ++. ( structs, ) sizeof , ( , ++).

a struct : " , " (C99, Β§6.7.2.1/16).

, , .

0
source

All Articles