1.sizeof关键字
1.1简单用法
sizeof 为C语言的一个主要关键字,而并非是一个函数,虽然其后经常会跟着一对括号,这就导致许多人认为这是一个函数,进而产生误解。用途:求某一特定的变量、指针、结构体、枚举、联合体等所占内存空间的大小。
1.2示例:
#include<iostream>
using namespace std;
int main()
{
char str1[]={'h','e','l','l','o'};
cout<<"str1="<<str1<<endl;
char str2[100]={'h','e','l','l','o'};
cout<<"str2="<<str2<<endl;
char str3[]="hello";
cout<<"str3="<<str3<<endl;
cout<<"size of str1="<<sizeof(str1)<<endl;
cout<<"size of str2="<<sizeof(str2)<<endl;
cout<<"size of str3="<<sizeof(str3)<<endl;
return 0;
}
这些基本数类sizeof所求的内存空间大小受到不同系统的约束。例如:在64位系统下,其大小分别为:
输出如下:环境为win10+Dev c++
基本知识:
用{}列举如str1用sizeof为真实长度并没有在末尾添加‘\0’.
但直接写字符串会在末尾添加\n.sizeof的结果会大一个字符。
1.3strlen函数与sizeof的区别
strlen 是一个函数,它用来计算指定字符串 str 的长度,但不包括结束字符(即 null 字符)。
看如下代码:
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char str1[]={'h','e','l','l','o'};
cout<<"str1="<<str1<<endl;
char str2[]="hello";
cout<<"str2="<<str2<<endl;
char str3[100]={'h','e','l','l','o'};
cout<<"str3="<<str3<<endl;
cout<<"sizeof str1="<<sizeof(str1)<<endl;
cout<<"sizeof str2="<<sizeof(str2)<<endl;
cout<<"strlen str2="<<strlen(str2)<<endl;
cout<<"strlen str3="<<strlen(str3)<<endl;
cout<<"sizeof str3="<<sizeof(str3)<<endl;
return 0;
}
由此可以看出:
strlen()得到的是字符串的真实长度,而sizeof是得到字符串在定义时在内存里开辟的大小。