[C Language-Array] The difference between string array and character array

#define _CRT_SECURE_NO_WARNINGS  1
#pragma warning(disable:6031)

#include<stdio.h>

int main()
{
	char arr1[ ] = "hello";                      // h e l l o \0             
	char arr2[ ] = { 'h','e','l','l','o' };      // h e l l o
	char arr3[ ] = { 'h','e','l','l','o','\0' }; // h e l l o \0

	printf("arr1=%s\n", arr1);//arr1=hello
	printf("arr2=%s\n", arr2);//arr2=hello烫烫烫烫烫蘦ello
	printf("arr3=%s\n", arr3); //arr3 = hello

	printf("arr1=%d\n", strlen(arr1));
	printf("arr2=%d\n", strlen(arr2));
	printf("arr3=%d\n", strlen(arr3));

	return 0;
}

Differences in printout:

arr1[] is a string array, which is a special array expression form, using double quotes "" . By default, there is '\0' at the end of the string hello. printft() only prints the characters before \0.

arr2[] is an ordinary character array, which stores the five characters hello. However, printf() will only stop printing when it encounters '\0' during printing, so garbled characters will be printed after hello.

arr3[] adds a '\0' at the end, which achieves the same function as arr1, except that arr1 adds '\0' by default, while arr3[] achieves the same function by adding it manually.

Find the difference in array lengths:

The same is true when calculating the length of the character array. strlen() counts the number of characters before \0, and arr2 prints out 21 bytes, which is exactly the same as the number displayed by printing (one Chinese character occupies two bytes ).

Guess you like

Origin blog.csdn.net/ggbb_4/article/details/129175096