C語言中如何計算一個數組佔內存多少空間?

C語言中有一個專門用於檢測類型或變量或數組在內存中所佔有的空間(字節數)的操做符sizeof,用它能夠直接檢測出數組在內存佔有的字節數。語法規則是:sizeof(x);(識別沒有歧義時也可寫成sizeof x;)——其中x是類型名、變量名或數組名等,返回x所佔字節數(int型)。如下代碼能夠幫助理解:數組

 1 #include "stdio.h"
 2 struct X{  3     int d;  4     float t;  5     double b;  6     char n[100];  7 };  8 int main(int argc,char *argv[]){  9     int a[]={1,2,3,4,5,6,7,8,9,10}; 10     double y=3.1415926; 11     struct X t[3]={{0,0.0f,0.0,""},};//結構體數組屬複雜類型
12     printf("10 elements of int array needs %d bytes.\n",sizeof a);//檢測整型數組
13     printf("Double variables of type need %d bytes.\n",sizeof(y));//double類型變量
14     printf("Type float need %d bytes.\n",sizeof(float));//float類型
15     printf("Structure array 't[3]' need %d bytes.\n",sizeof t);//檢測複雜類型
16     return 0; 17 }
相關文章
相關標籤/搜索