How to learn C language initially (3)

4. String + escape character

4.1 Strings

"abcd"

A string of characters enclosed in double quotes like this is called a string literal, or string for short.
The end of the string is an escape character \0 (hidden). \0 is the end mark when calculating the length of the string, which takes up space, but not as the content of the string.

Observe the code below to see the difference in the output? Why? (highlights the importance of \n)

#include <stdio.h>
int main()
{
    
    
	char arr1[] = "abcd";//[]里的内容是字符串的空间,不写时系统会自动生成合适的空间大小。
	char arr2[] = {
    
     'a','b','c','d' };
	char arr3[] = {
    
     'a','b','c','d','\0' };
	printf("%s\n",arr1);//%s是字符串的打印字符
	printf("%s\n",arr2);
	//由于没有结束标志\0,在输出完abcd后仍然会输出数据,直到在电脑存储空间中找到\0。
	//由于电脑存储空间abcd后的数据未知,所以字符串的输出结果和空间大小为随机值。
	printf("%s\n",arr3);
	return 0;
}

as the picture shows:
insert image description here

4.2 Escape characters

If we want to print a directory: c:\code\test.c
we usually print like this:

#include <stdio.h>
int main()
{
    
    
	printf("c:\code\test.c\n");
	return 0;
}

But the actual result is this:
insert image description here
the reason for this situation is that there are escape characters in this string of directory data.

The escape character, as the name suggests, is to change the meaning.
Here are some escape characters
The picture comes from the Internet
, so if you want to output: c:\code\test.c
should be like this:

#include <stdio.h>
int main()
{
    
    
	printf("c:\\code\\test.c");
	return 0;
}

insert image description here

5. Notes

  1. Unneeded code can be deleted directly or commented out.
  2. Some codes are more difficult to understand, you can add comment text.

Comments come in two flavors:

  • C-style comments / xxxxxx /
    defect: cannot nest comments
  • C++ style comments //xxxxxxxx
    can comment one line or multiple lines

Guess you like

Origin blog.csdn.net/xue_bian_cheng_/article/details/131499504