strlen、sizeof区别

strlen、sizeof区别
sizeof计算 包括   "/0"
strlen计算 不包括 "/0"

sizeof遇到 最后一个 "/0"停止
strlen遇到 第一个   "/0"停止

char str[20]="0123456789";
sizeof(str);	// 20
strlen(str);	// 10	

char *ss = "0123456789";
sizeof(ss);		// 4  指针ss的空间大小
sizeof(*ss);	// 1  第一个字符‘0’占的空间
strlen(ss);		// 10 字符串长度
  • SizeofStrlen.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include <bits/wordsize.h>  //
 
int main()
{ 
    char *s = "helloworld";
    char a[30] = "";
    char b[] = "***";
    char d[] = "helloworld";    // sizeof 会计算在后面添加的 \0
    char e[] = {'h','e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'};

    printf("s: %d %d\n", sizeof(*s), strlen(s));
    printf("d: %d %d\n", sizeof(d), strlen(d));
    printf("e: %d %d\n", sizeof(e), strlen(e));

    char  str[] = "\\\0";
    char *p = str;
    int   n = 1000;
    printf("str:%d\n p:%d\n %d\n %d\n", sizeof(str), sizeof(p), sizeof(n), strlen(str));

    double doub = 3.1415926;
    printf("double: %d\n", sizeof(doub));
    
    unsigned long pulArray[]= {6,7,8,9,10};
    unsigned long *pulPtr;    

    char c1[]={'I',' ','a','m',' ','h','a','p','p','y','\0'};
    char c2[]="I am happy";
    printf("c1: %d %d %s\n", sizeof(c1), strlen(c1), c1);
    printf("c2: %d %d\n", sizeof(c2), strlen(c2));

    pulPtr = pulArray;
    *(pulPtr+2)+=2;
    printf("p: %d,%d\n", *pulPtr, *(pulPtr+2));

    if(__WORDSIZE == 32)
    {
        printf("machine 32bit\n");
    }

    if(__WORDSIZE == 64)
    {
        printf("machine 64bits\n");
    }

    printf("a: %d %d\n", sizeof(a), strlen(a));
    memcpy(a, s, strlen(s)+1);
    printf("%s\n", a);

    printf("%d\n", sizeof(int));
    
    memcpy(d, b, strlen(b));   // strlen(b)+1 
    printf("%s\n", d);

    return 0;
}

  • 运行结果
s: 1 10
d: 11 10
e: 10 10
str:3
 p:8
 4
 1
double: 8
c1: 11 10 I am happy
c2: 11 10
p: 6,10
machine 64bits
a: 30 0
helloworld
4
***loworld

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值