记录一个之前没有遇到的知识点:
区别 1. strlen && sizeof:strlen在计算字符串长度时不包含'\0'空字符;sizeof包含空字符
区别 2. 字符串作为指针传入函数:函数内部调用sizeof计算传入字符串长度不可行,此时获取的为变量地址的长度永远是8个字节(4个字节如果是32位系统); 但strlen不受影响,无论在函数内部和外部;
新增:区别 3.当创建一个固定长度数组接收一个不定长字符串时。使用sizeof计算的永远时数组创建的大小。如下面例子:example[10] 永远时10个char大小。但是strlen 会计算‘\0’作为结尾实际字符串的大小。
#include <stdio.h>
#include <string.h>
void example(char*string)
{
int size=sizeof(string);
int str_len=strlen(string);
printf("the sizeof inside function: %d\n",size);
printf("the strlen inside function: %d\n",str_len);
}
int main()
{
//example 1 & 2
char a[]="123456789";
int size=sizeof(a);
int str_lenth=strlen(a);
printf("the sizeof outside of function %d\n",size);
printf("the strlen outside of function %d\n",str_lenth);
example(a);
//example 3
char example[10]="1";
int strlen_example = strlen(example);
int sizeof_example = sizeof(example);
printf("strlenth of array[10]: %d \n",strlen_example);
printf("sizeof of array[10]: %d \n",sizeof_example);
return 0;
}
the sizeof outside of function 10
the strlen outside of function 9
the sizeof inside function: 8
the strlen inside function: 9
strlen of array[10]: 1
sizeof of array[10]: 10

4108

被折叠的 条评论
为什么被折叠?



