The difference between strlen() and sizeof() in C language

First, let’s take a look at the two pieces of code

half search

//折半查找


#include<stdio.h>

int main()
{

	int arr[10] = { 2,3,5,6,7,9,14,21,25,26 };
	int k = 26;
	int size = sizeof(arr) / sizeof(arr[0]);
	int left = 0;
	int right = size - 1;
	while (left<=right)
	{
		int mid = (left + right) / 2;
		if (arr[mid]<k)
		{
			left = mid + 1;

		}
		else if (arr[mid]>k)
		{
			right = mid - 1;
		}
		else
		{
			printf("找到了,下标是%d\n", mid);
			break;
		}
	}
	if (left>right)
	{
		printf("找不到");
	}
	return 0;
}

 When searching by half, the size of the array is found using 

int size = sizeof(arr) / sizeof(arr[0])

 Divide the overall size of the array by the size of the elements to get the number of elements

Characters separated from both sides



//字符从两边向中间展开

#include<stdio.h>
#include<Windows.h>

int main()
{
	char arr1[] = "mo yu yi shu jia niu bi !!!";
	char arr2[] = "***************************";
	int left = 0;
	int right = strlen(arr1) - 1;
	/*int right= sizeof(arr1)/sizeof(arr1[0])-2*/
	while (left<=right)
	{
		arr2[left] = arr1[left];
		arr2[right] = arr1[right];
		printf("%s\n", arr2);
		Sleep(99);
		left++;
		right--;
	}
	return 0;

}

 In this code, strlen() is used, (the sizeof() code has been written)

Summarize

#include<stdio.h>

int main()
{
	int arr1[] = { 4,5,6,3,2,1,5,6,9 };
	char arr2[] = "moyuyishujia";

	int a1 = strlen(arr1);
	//strlen只能求字符串长度,不包含结尾空字符\0

	int b1 = strlen(arr2);
	//标准的strlen求字符串长度 预测输出为 12

	int a2 = sizeof(arr1) / sizeof(arr1[0]);
	//求数组元素个数 预测输出为 9

	int b2 = sizeof(arr2) / sizeof(arr2[0]);
	//求字符串个数,由于sizeof包含最后空字符\0,故预测结果为 13

	printf("a1=%d b1=%d a2=%d b2=%d", a1, b1, a2, b2);
	return 0;
}

 

The sizeof() function is used to calculate the size of a data type or variable. It can be used for any type of calculation and returns the number of bytes. 
The strlen() function is used to calculate the length of a string. It can only be used for strings terminated by null characters. It returns the number of characters.

Guess you like

Origin blog.csdn.net/weixin_51345015/article/details/134065657