点击上方公众号关注,关注更多分享动态
✎ 编 者 悟 语有些事需要的是过去,不是人的问题,而是时间的问题 ,这就是形式。
文 章 导 读
今天给大家讲解了下sizeof关键字与strlen函数的功能及使用,并进行了实例代码对比测试,希望对大家有所益处哈!
1sizeof关键字1)sizeof的功能
它是可以测试数组、指针、类型、变量、函数等对象大小的一个C语言关键字。返回的类型为unsigned int,用typedef定义。
2)sizeof是关键字还是函数
sizeof是关键字而不是函数,主要体现是sizeof测量变量的空间时,可以省略括号,即此时就能证明它不是函数,后面的测试代码中会注明。
sizeof在计算类型大小时是不能省略括号的。
测试的类型的大小在不同的编译系统下大小是不同的,比如32位的可能是4个字节,我的64位系统测试是8个字节。
2strlen函数1)函数功能
计算指针s指向字符串的长度。
strlen测试就是字符串的长度,有些代码中会出现strlen(s)-1的处理,主要是因为数组等操作上,数组下标是从0开始,这样做就是为了防止数组越界。
2)头文件
#include
3)函数原型
size_t strlen(const char *s)
4)返回值
返回终止的空字符前面的字符的数量。
3sizeof与strlen的对比测试代码
#include
#include
#include
int main(int argc, char *argv[])
{
char *pchar = "dfghs",ch = 'a';
int test1,test2,test3,test4,test5,test6,test7,test8,test9;
char str[10] = "abcdefg";
int num1,num2,num3,*pint;
int stru1,stru2,stru3;
int num = 10;
float *pfloat,fnum = 2.0;
double *pdouble,dnum = 4.0;
struct stru1
{
char a;
char b;
// int c;
// float f;
}stru_val1;
struct stru2
{
char a;
char b;
int c;
// float f;
}stru_val2;
struct stru3
{
char a;
char b;
int c;
float f;
}stru_val3;
// ## 1.sizeof测试数据类型
printf("\n## 1 sizeof测试数据类型\n");
// 1)sizeof后面不加括号也没问题
test1 = sizeof ch;
test2 = sizeof(ch);
printf("\n字符类型sizeof不是函数验证:\n%d\n%d\n",test1,test2);
// 2) 测试整型数据
test3 = sizeof(num);
printf("\nsizeof测试整型数据:\n%d\n",test3);
// 3)测试float类型数据
test4 = sizeof(fnum);
printf("\nsizeof测试float类型数据:\n%d\n",test4);
// 4) 测试double类型数据
test5 = sizeof(dnum);
printf("\nsizeof测试double类型数据:\n%d\n",test5);
// ## 2.sizeof测试指针类型
printf("\n## 2 sizeof测试指针类型\n");
// 5)测试字符指针
test6 = sizeof(pchar);
printf("\nsizeof测试字符指针:\n%d\n",test6);
// 6)测试整型指针
test7 = sizeof(pint);
printf("\nsizeof测试整型指针:\n%d\n",test7);
// 7)测试float类型指针
test8 = sizeof(pfloat);
printf("\nsizeof测试float指针类型:\n%d\n",test8);
// 8) 测试double类型指针
test9 = sizeof(pdouble);
printf("\nsizeof测试double指针类型:\n%d\n",test9);
// ## 3.sizeof与strlen对比测试
printf("\n## 3 sizeof与strlen对比测试\n");
num1 = strlen(str);
printf("\nstrlen函数验证,输出str数组中字符串abcdefg的大小:\n%d\n",num1); // 返回空字符为结束符的字符串中字符的个数
num2 = sizeof(str);
printf("\nsizeof关键字与strlen函数对比,sizeof输出数组长度:\n%d\n",num2);
num3 = strlen(pchar);
printf("\nstrlen函数验证,输出str数组中字符串dfghs的大小:\n%d\n",num3);
// ## 4.结构测试
printf("\n## 4 结构测试\n");
stru1 = sizeof(stru_val1);
printf("\n测试结构1的大小:\n%d\n",stru1); //结构体大小存在字节对齐的问题,小字节类型会向大字节靠拢,测试时可以注释,取消注释进行组合测试
stru2 = sizeof(stru_val2);
printf("\n测试结构2的大小:\n%d\n",stru2);
stru3 = sizeof(stru_val3);
printf("\n测试结构3的大小:\n%d\n",stru3);
return 0;
}
运行结果如下:
总结
今天先给大家讲解下sizeof关键字和strlen函数的功能及使用,用代码进行了使用测试,经过对比,大家会对这两个容易混淆的内容有一个更清晰的认识,后面还会有C语言相关的讲解测试内容,大家敬请期待哈,。
有问题可以后台留言交流,公众号18年后新申请的,文章后不支持留言功能的。
相关文章:
内存分配函数malloc、calloc、realloc的功能测试
static关键字的3种特性
用结构体和指针模拟配置芯片引脚输出高低电平
C标准库函数sprintf和sscanf的使用
用Dev-C++生成dll动态链接库文件并用C代码调用
宏分类的妙用(排版开始用模板)
进化论——从函数指针到被结构封装的函数指针及参数的应用举例
专辑推荐:
Python技能专辑
C语言专辑
IDE调试专辑
软件推荐专辑
软实力专辑
扫码关注我们
❖ Game Over!