用sizeof求各数据类型在内存中的大小以及sizeof与strlen的比较

来源:互联网 发布:西安行知中学军训吗 编辑:程序博客网 时间:2024/05/16 05:28

<span style="font-size:18px;">#include<stdio.h>#include<string.h>void main(){char name[30]="zhang";char s[]="jddeif";char *p;printf("int:%d bytes\n",sizeof(int));/*4*/printf("long:%d bytes\n",sizeof(long));/*4*/printf("short:%d bytes\n",sizeof(short));/*2*/printf("char:%d bytes\n",sizeof(char));/*1*/printf("float:%d bytes\n",sizeof(float));/*4*/printf("double:%d bytes\n",sizeof(double));/*8*/printf("long double:%d bytes\n",sizeof(long double));/*8*/printf("name:%d bytes\n",sizeof(name));/*30*/printf("name:%d bytes\n",strlen(name));/*5*/printf("s:%d bytes\n",sizeof(s));/*7*/printf("s:%d bytes\n",strlen(s));/*6*/printf("p:%d bytes\n",sizeof(p));/*4*/printf("*p:%d bytes\n",sizeof(*p));/*1*/}</span>

从上述程序可知,sizeof()的作用是返回一个对象或一个类型在内存中所占字节数的多少。与strlen()对比可知,strlen()的功能只限于计算字符数组在“\0”之前的字符数。当字符数组定义未标明长度时,sizeof()计算的是字符加“\0”总共的字符数。

指针类型所占的内存为4个字节,而*p的内存大小就要根据所定义的类型而定。
0 0