[First knowledge of C language] basic knowledge points and usage of sizeof and strlen

1.sizeof

(1) If you want to find the size of the space occupied by the string, including the default'\0' at the end of the string.
(2) If what you are looking for is not the size of a string, what you are looking for is the size of an array, type, etc., without considering'\0', because it is not a string, there is no default'\0' at the end.
(3) If'\0' obviously appears, count it.
(4) Return the size of a variable or type (in bytes)

2.strlen

Find the size of the string content, count the number of characters in the string, stop counting when encountering'\0', and do not count'\0'.

3. Knowledge points

3.1 For arrays

sizeof: The result is the size of the array.
strlen: The entire array will be traversed during calculation, and'\0' may not be encountered when traversing later. There will be out-of-bounds problems. Either the program crashes or random values ​​are generated, but the result must be at least the length of the array.

3.1.1 There is no'\0' in the array

#include <stdio.h>

int main()
{
    
    
	char s[] = {
    
     'a', 'b', 'c' };
	printf("%d\n", sizeof(s));
	printf("%d\n", strlen(s));//随机值

	return 0;
}

Insert picture description here

3.1.2 The array has'\0'

(1)'\0' is at the end

#include <stdio.h>

int main()
{
    
    
	char s[] = {
    
     'a', 'b', 'c', '\0' };
	printf("%d\n", sizeof(s));
	printf("%d\n", strlen(s));

	return 0;
}

Insert picture description here

(2)'\0' is in the middle

#include <stdio.h>

int main()
{
    
    
	char s[] = {
    
     'a', 'b','\0','c', };
	printf("%d\n", sizeof(s));
	printf("%d\n", strlen(s));

	return 0;
}

Insert picture description here

3.2 For strings

3.2.1 The string has no obvious'\0'

#include <stdio.h>

int main()
{
    
    

	printf("%d\n", sizeof("abcd"));
	printf("%d\n", strlen("abcd"));

	return 0;
}

Insert picture description here

3.2.2 The string has obvious'\0'

(1)'\0' is at the end

#include <stdio.h>

int main()
{
    
    
	printf("%d\n", sizeof("abd\0"));
	printf("%d\n", strlen("abd\0"));

	return 0;
}

Insert picture description here

(2)'\0' is in the middle

#include <stdio.h>

int main()
{
    
    
	printf("%d\n", sizeof("abc\0d"));
	printf("%d\n", strlen("ab\0d"));

	return 0;
}

Insert picture description here

Guess you like

Origin blog.csdn.net/m0_46630468/article/details/113200852