[C/C++] 如何計算陣列大小/個數

最近在寫 BCB 的時候遇到的,不過忘記之前怎麼寫的,所以又上去找了一下,發現可以利用 sizeof 這個函式,來計算陣列的個數,我去查了一下 BCB 的 manual,裡面寫的還蠻詳細的,如下

Example for sizeof operator

/ USE THE sizeof OPERATOR TO GET SIZES OF DIFFERENT DATA TYPES. /

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <stdio.h>
struct st {
   char *name;
   int age;
   double height;
};

struct st St_Array[]= {  /* AN ARRAY OF structs */
   { "Jr.",     4,  34.20 },  /* St_Array[0] */
   { "Suzie",  23,  69.75 },  /* St_Array[1] */
};

int main()
{
   long double LD_Array[] = { 1.3, 501.09, 0.0007, 90.1, 17.08 };

   printf("\nNumber of elements in LD_Array = %d",
           sizeof(LD_Array) / sizeof(LD_Array[0]));

   /****  THE NUMBER OF ELEMENTS IN THE St_Array. ****/

   printf("\nSt_Array has %d elements",
           sizeof(St_Array)/sizeof(St_Array[0]));

   /****  THE NUMBER OF BYTES IN EACH St_Array ELEMENT.  ****/
   printf("\nSt_Array[0] = %d", sizeof(St_Array[0]));

   /****  THE TOTAL NUMBER OF BYTES IN St_Array.  ****/   
      printf("\nSt_Array=%d", sizeof(St_Array));
   return 0;

}

Output

1
2
3
4
5
6
Number of elements in LD_Array = 5

St_Array has 2 elements
St_Array[0] = 16

St_Array= 32

See also