[C Language] The difference between strlen and sizeof

The difference between strlen and sizeof:

  1. There is no connection between strlen and sizeof

  2. strlen is used to find the length of a string - it can only be used to find the length of a string - library function - use the header file

  3. sizeof calculates the size of variables, arrays, and types - the unit is bytes - operator

About the calculated results

char arr1[] = “abc”;
char arr2[] = {
    
    'a','b','c'};

sizeof includes '/0', and strlen does not include '/0'. If there is no '/0' in the initialization, the result of strlen will be a random value.

so

sizeof(arr1) = 4;
sizeof(arr2) = 3;
strlen(arr1) = 3;
strlen(arr2) = 随机值;

sizeof calculates the size of the memory space occupied by the variable, the unit is bytes

The size of the pointer is either four bytes or eight bytes, 4 bytes on 32-bit platforms

#include <stdio.h>

int main()
{
    
    
	int a = 0;
	char b = 'A';
	int arr[10] = {
    
     0 };
	printf("%d\r\n", sizeof(a));	   //4
	printf("%d\r\n", sizeof(int));     //4

	printf("%d\r\n", sizeof(b));	   //1	
	printf("%d\r\n", sizeof(char));    //1

	printf("%d\r\n", sizeof(arr));     //40
	printf("%d\r\n", sizeof(int [10]));//40
	return 0;
}

The contents in sizeof will not be subjected to actual operations.

#include <stdio.h>

int main()
{
    
    
	short s = 0;
	int a = 10;
	printf("%d\n", sizeof(s = a + 5));//2
	printf("%d\n", s);//0
	return 0;
}

Guess you like

Origin blog.csdn.net/Daears/article/details/127424252