sizeof作用于数组和指针以及sizeof和strlen的区别

代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
        char str[] = "hello";
        char* p1 = "hello";
        char* p2 = "hello";
        int size_str = 0;
        int size_p1 = 0;
        int size_p2 = 0;
        int len_str = 0;
        int len_p = 0;

        size_str = sizeof(str);
        size_p1 = sizeof(p1);

        p2 = (char*)malloc(100);
        size_p2 = sizeof(p2);

        len_str = strlen(str);
        len_p = strlen(p1);

        printf("size_str = %d\n",size_str);
        printf("size_p1 = %d\n",size_p1);
        printf("size_p2 = %d\n",size_p2);
        printf("len_str = %d\n",len_str);
        printf("len_p = %d\n",len_p);

        return 0;
}

运行结果:

 

总结:

① 用sizeof,只要是指针,无论什么类型 ,无论是否用malloc,无论malloc开辟了多大空间,在32位下结果永远是4,在64位下永远是8.

②sizeof计算字符数组大小,会将'\0'也计算在内,比如字符数组中是"hello"6个字符,那么结果是6,因为还有一个'\0'要算在内。其实严格来讲应该这样的:sizeof(str)/sizeof(char)           或 sizeof(str)/sizeof(str[0]),这样才是这个数组的大小,因为char形占一个字节,所以除不出无所谓。

③ 用strlen,他只计算里面字符的个数,到'\0'结束,'\0'这个字符不计算在内

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值