Are you really clear about sizeof and strlen?

The following is largely excerpted from https://blog.csdn.net/magic_world_wow/article/details/80500473
Thanks for the good article, no longer confused.


the difference

  1. The result type of the sizeof operator is size_t, which is defined as an unsigned int type by typedfe in the header file. This type is guaranteed to accommodate the byte size of the largest object created by the implementation, and the calculation is the actual number of bytes in the allocated space. The result type of strlen is also size_t (size_t strlen( const char *string )), but strlen is the number of characters in the calculated space (not including '\0').
  2. sizeof is an operator that can use types or functions as parameters. strlen is a function, must use char* (string) as a parameter, and must end with ''\0''.
    for example:
int function();
printf("%d",sizeof(function()));//sizeof可以使用函数做参数
  1. sizeof calculates the result when compiling, and is the number of bytes in the space occupied by the type, so when the array name is used as a parameter, the size of the entire array is calculated. However, strlen starts to calculate the result when it is running. This means that the calculated result is no longer the size of the memory occupied by the type, and the array name degenerates into a pointer.

  2. sizeof cannot calculate the size of dynamically allocated space.

Examples of specific differences are as follows:

	char* ss = "0123456789";
	printf("%d\n",sizeof(ss));//结果为8,ss是指向字符串常量的字符指针,sizeof 获得的是一个指针占的空间,应该是长整型的。
	printf("%d\n",sizeof(*ss));//结果为1 计算第一个char字符数据所占用的空间,为1
	printf("%d\n",strlen(ss));//结果为10 计算数据的实际大小,在\0之前截止
	printf("%d\n",strlen(*ss));//段错误  strlen是函数,只能以char*(字符串)做参数


char s[] = "0123456789";
sizeof(s);     //结果 11   ===》s是数组,计算到\0位置,因此是10+1
strlen(s);     //结果 10   ===》有10个字符,strlen是个函数内部实现是用一个循环计算到\0为止之前
sizeof(*s);    //结果 1    ===》*s是第一个字符

char s[100] = "0123456789";
sizeof(s);     //结果是100 ===》s表示在内存中的大小 100×1
strlen(s);     //结果是10  ===》strlen是个函数内部实现是用一个循环计算到\0为止之前

int s[100] = "0123456789";
sizeof(s);     //结果 400  ===》s表示再内存中的大小 100×4
strlen(s);     //错误      ===》strlen的参数只能是char* 且必须是以‘\0‘结尾的

char q[]="abc";
char p[]="a\n";
sizeof(q),sizeof(p),strlen(q),strlen(p);\\结果是 4 3 3 2

char p[] = {
    
    'a','b','c','d','e','f','g','h'};
char q[] = {
    
    'a','b','c','d,'\0','e','f','g'};
sizeof(p);     //结果是8 ===》p表示在内存中的大小 8×1
strlen(p);     //为一个随机值,结果与编译器有关,不同编译器结果一般不同
sizeof(q);     //结果是8 ===》p表示在内存中的大小 8×1
strlen(q);     //结果为4 ===》存在'\0',遇到'\0'计算停止。

Summarize

*sizeof is an operator and strlen is a function.
*sizeof can take types as parameters, such as int char.
strlen can only use char * as a parameter and ends with \0.
*sizeof does not degenerate when it is an array, and the array will be degenerated into a pointer when passed to strlen.

Guess you like

Origin blog.csdn.net/qq_44333320/article/details/125697739