c strlen和sizeof详解

时间:2022-07-20 06:20:05

用双引号定义并且声明的时候明确指定数组大小的话,sizeof就会返回指定的大小,不会自动加1;

char str2[10] = "hello c";
printf("strlen = %ld\n", strlen(str2));
printf("sizeof = %ld\n", sizeof(str2));
//strlen = 7
//sizeof = 10

用大括号定义并且声明的时候明确指定数组大小的话,sizeof就会返回指定的大小,不会自动加1;

char str5[10] = {'h','e','l','l','o',' ','C'};
printf("strlen = %ld\n", strlen(str5));
printf("sizeof = %ld\n", sizeof(str5));
//strlen = 7
//sizeof = 10

用双引号定义并且声明的时候没有明确指定数组大小的话,sizeof就会是实际的大小+1;strlen也正常

char str1[] = "hello c";
printf("strlen = %ld\n", strlen(str1));
printf("sizeof = %ld\n", sizeof(str1));
//strlen = 7
//sizeof = 8

用大括号定义并且声明的时候没有明确指定数组大小的话,sizeof就会是实际的大小(不加1);但是strlen就变得诡异了,而且每次执行的结果的不一样

char str4[] = {'h','e','l','l','o',' ','C'};
printf("strlen = %ld\n", strlen(str4));
printf("sizeof = %ld\n", sizeof(str4));
//strlen = 14
//sizeof = 7

用双引号定义并且声明的时候明确指定数组大小,比实际的小的话,sizeof就会返回指定的大小,不会自动加1;但是strlen就变得诡异了,而且每次执行的结果的不一样

char str3[5] = "hello c";
printf("strlen = %ld\n", strlen(str3));
printf("sizeof = %ld\n", sizeof(str3));
//strlen = 12 strlen就变得诡异了,而且每次执行的结果的不一样
//sizeof = 5
char cr[] = {'a','b','\0','c',};
char cr1[] = {'a','b',0,'c',};
printf("cr strlen = %ld\n", strlen(cr));
printf("cr1 strlen = %ld\n", strlen(cr1));
printf("cr sizeof = %ld\n", sizeof(cr));
//cr strlen = 2
//cr1 strlen = 2
//cr sizeof = 4

通过以上的代码可以得出以下结论

  • strlen的原理是一直计数,直到遇到'\0'为止
  • 用双引号定义时,会在最后自动加上'\0'
  • 用大括号定义时,不会在最后自动加上'\0'
  • 用大括号定义时,如果声明的数量大于大括号里的数量,会在最后用'\0'填补缺失的位数
  • '\0' = 0

全局变量存放在静态区,静态区的初始值都是'\0',所以strlen(str6)为0

char str6[10];
int main(){
printf("strlen = %ld\n", strlen(str6));
printf("sizeof = %ld\n", sizeof(str6));
}
//strlen = 0
//sizeof = 10

局部变量存放在栈区,栈区的初始值都是随机的,所以strlen(str6)为随机值

char str7[10];
printf("strlen = %ld\n", strlen(str7));
printf("sizeof = %ld\n", sizeof(str7));
//strlen = 12(随机值)
//sizeof = 10

以指针形式定义的话,sizeof返回的永远是指针的大小

char *p = "hello C";
printf("strlen = %ld\n", strlen(p));
printf("sizeof = %ld\n", sizeof(p));
//strlen = 7
//sizeof = 8
char *p1[3] = {"hello C","abcd","12345"};
printf("p1 strlen = %ld\n", strlen(*p1));//7
printf("p1 strlen = %ld\n", strlen(*(p1+1)));//4
printf("p1 strlen = %ld\n", strlen(*(p1+2)));//5
printf("p1 sizeof = %ld\n", sizeof(p1));//24 因为p1不是指针,p1是指针数组,数组里有3个指针所以3 * 8 = 24
char (*p2)[3000];
printf("p2 sizeof = %ld\n", sizeof(p2));//8 因为p2是数组指针,所以不管数组大小是多少,值都是8

函数的参数是数组时,有个经典的骗局,虽然fun函数的参数是数组,但是c语言不会在复制一个数组给形参,它会实际传递的是数组的首地址。

#include <stdio.h>
#include <string.h> void fun(char str[]){//等同于void fun(char* str),所以sizeof(str)的值为8
printf("strlen = %ld\n", strlen(str));
printf("sizeof = %ld\n", sizeof(str));
}
int main(){
char str[10] = "Hello C";
printf("strlen = %ld\n", strlen(str));
printf("sizeof = %ld\n", sizeof(str));
printf("-------------------------------------\n");
fun(str);
}
执行结果:
strlen = 7
sizeof = 10
-------------------------------------
strlen = 7
sizeof = 8