The respective functions of strlen function and sizeof and the difference between the two

strlen function

The function of the strlen function: get the effective length of the string
The return value of the strlen function: the effective length of the string (in bytes) The
strlen function stops when encountering '\0', and the calculation result does not include '\0', and
the string function needs to be quoted Header file: #include<string.h>

Here are some examples for your further understanding:

#include<stdio.h>
#include<string.h>   //不要忘了引用字符串函数头文件
int main()
{
    
    
	char arr[] = "abcdefg";  //创建一个数组,以字符串abcdefg为例
	int ret = strlen(arr);     //用一个int型变量接收  从a开始向后读,只到遇到'\0'停止,不包括'\0',是7个字节
	printf("%d", ret);         //打印字符串返回值
//  printf("%d",strlen(arr));	 也可以像这样直接打印
 	return 0;          
}

The output is:
insert image description here

string: The string is written in double quotes and ends with '\0', but '\0' is not displayed. As in the above "abcdefg", there is a hidden '\0' after g.

sizeof

The role of sizeof: Calculate the size of the space occupied by the variable or type in memory
The return value of sizeof: The size of the space occupied by the variable or type in memory (in bytes)

It should be noted that sizeof is not a function, but an operator (such as "+" is an operator).
Here are some examples for your further understanding:

#include<stdio.h>
int main()
{
    
    
	printf("%d\n",sizeof(char));      //计算char类型在内存中占几个字节
	printf("%d\n",sizeof(short));     //计算short类型在内存中占几个字节
	printf("%d\n",sizeof(int));       //计算int类型在内存中占几个字节  
	return 0;
}

The output is:
insert image description here

The difference between strlen function and sizeof

#include<stdio.h>
#include<string.h>  //引用字符串函数头文件
int main()
{
    
    
	char arr[] = "abcdefg";        
	printf("%d\n", strlen(arr));   //从a向后读取,到'\0'停止,不包括'\0',为7个字节
	printf("%d\n", sizeof(arr));   //从a向后读取,获取数组的总大小,包括'\0',为8个字节
	return 0;
}

The core difference is that strlen does not include '\0', sizeof includes '\0' and
the output result is:
insert image description here

Finally, I would like to give you some suggestions when using it:
1. The strlen function can only be used to calculate the effective length of a string, which must be kept in mind
2. When using the strlen function, don’t forget to quote the header file #include<string.h>
ps: The above are all mistakes bloggers have made.

Guess you like

Origin blog.csdn.net/qq_73390155/article/details/129642079