测试Case:
- #include
- #include
-
- 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