Linux C 字符串的sizeof与strlen的区别

测试Case:

#include <string.h>
#include <stdio.h>

void test_sizeof_and_strlen_for_linux_c()
{
    char a[10] = "abc";
    printf("sizeof(a):%ld strlen(a):%ld\n", sizeof(a), strlen(a));

    char b[10] = {'a', 'b', 'c'};
    printf("sizeof(b):%ld strlen(b):%ld\n", sizeof(b), strlen(b));

    char c[10] = {'a', 'b', 'c', '0'};
    printf("sizeof(c):%ld strlen(c):%ld\n", sizeof(c), strlen(c));

    char d[10] = {'a', 'b', 'c', '\0'};
    printf("sizeof(d):%ld strlen(d):%ld\n", sizeof(d), strlen(d));

    char e[10] = {'a', 'b', 'c', 0, 'd'};
    printf("sizeof(e):%ld strlen(e):%ld\n", sizeof(e), strlen(e));

    char f[10] = "";
    printf("sizeof(f):%ld strlen(f):%ld\n", sizeof(f), strlen(f));

    char g[10] = {};
    printf("sizeof(g):%ld strlen(g):%ld\n", sizeof(g), strlen(g));

    char h[10];
    printf("sizeof(h):%ld strlen(h):%ld\n", sizeof(h), strlen(h));

    char i[] = {};
    printf("sizeof(i):%ld strlen(i):%ld\n", sizeof(i), strlen(i));

    char j[] = "";
    printf("sizeof(j):%ld strlen(j):%ld\n", sizeof(j), strlen(j));

    char k[] = "abc";
    printf("sizeof(k):%ld strlen(k):%ld\n", sizeof(k), strlen(k));

    char l[] = "abc0";
    printf("sizeof(l):%ld strlen(l):%ld\n", sizeof(l), strlen(l));

    char m[] = "abc\0";
    printf("sizeof(m):%ld strlen(m):%ld\n", sizeof(m), strlen(m));

    char n[10] = "abc";
    n[5] = '\0';
    printf("sizeof(n):%ld strlen(n):%ld\n", sizeof(n), strlen(n));

    char o[10] = "abc";
    o[4] = 'e',
    o[5] = '\0';
    printf("sizeof(o):%ld strlen(o):%ld\n", sizeof(o), strlen(o));

    char p[10] = "abc";
    p[3] = 'e',
    p[5] = '\0';
    printf("sizeof(p):%ld strlen(p):%ld\n", sizeof(p), strlen(p));

    char q[10] = "\0abc";
    printf("sizeof(q):%ld strlen(q):%ld\n", sizeof(q), strlen(q));

    char r[] = "\0abc";
    printf("sizeof(r):%ld strlen(r):%ld\n", sizeof(r), strlen(r));

    char s[10] = "abcdefghijklm";
    printf("sizeof(s):%ld strlen(s):%ld\n", sizeof(s), strlen(s));
}

int main()
{
    test_sizeof_and_strlen_for_linux_c();
    return 0;
}

测试结果:

:~/proj/test/test$ ./a.out 
sizeof(a):10 strlen(a):3
sizeof(b):10 strlen(b):3
sizeof(c):10 strlen(c):4
sizeof(d):10 strlen(d):3
sizeof(e):10 strlen(e):3
sizeof(f):10 strlen(f):0
sizeof(g):10 strlen(g):0
sizeof(h):10 strlen(h):0
sizeof(i):0 strlen(i):0
sizeof(j):1 strlen(j):0
sizeof(k):4 strlen(k):3
sizeof(l):5 strlen(l):4
sizeof(m):5 strlen(m):3
sizeof(n):10 strlen(n):3
sizeof(o):10 strlen(o):3
sizeof(p):10 strlen(p):4
sizeof(q):10 strlen(q):0
sizeof(r):5 strlen(r):0
sizeof(s):10 strlen(s):10

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值