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 }

 

posted @ 2018-06-22 13:28  波特曼  阅读(7652)  评论(0编辑  收藏  举报