简体   繁体   English

Printf function 也打印另一个字符串

[英]Printf function prints another string too

Hi i am fairly new in C language and i was trying to understand the strings.嗨,我是 C 语言的新手,我试图理解这些字符串。 As i know, strings are just an array of characters and there shouldn't be a difference between char a[]= "car" and char a[] = {'c','a','r'} .据我所知,字符串只是一个字符数组, char a[]= "car"char a[] = {'c','a','r'}之间应该没有区别。

When i try to print the string as:当我尝试将字符串打印为:

char a[] = "car";
char b[] = "testing the cars";
printf("%s", a);

the output is just car and there's no problem.But when i try to print it as: output 只是汽车,没有问题。但是当我尝试将其打印为:

char a[] = {'c','a','r'};
char b[] = "testing the cars";
printf("%s", a);

it's printing the b too.它也在打印 b 。 Can you explain what's the reason of it?你能解释一下这是什么原因吗?

The %s specifier of printf() expects a char* pointer to a null-terminated string. printf()%s说明符需要一个指向空终止字符串的char*指针。

In the first case, a and b are both null-terminated.在第一种情况下, ab都是空终止的。 Initializing a char[] array of unspecified size with a string literal will include the literal's null-terminator '\0' character at the end.使用字符串文字初始化未指定大小的char[]数组将在末尾包含文字的空终止符'\0'字符。 Thus:因此:

char a[] = "car";

is equivalent to:相当于:

char a[] = {'c', 'a', 'r', '\0'};

In the second case, a is NOT null-terminated, leading to undefined behavior , as printf("%s", a) will read past the end of a into surrounding memory until it eventually finds a '\0' character.在第二种情况下, a不是空终止的,导致未定义的行为,因为printf("%s", a)将读过a的末尾进入周围的 memory,直到它最终找到一个'\0'字符。 It just happens that, in your case, b exists in that memory following a , but that is not guaranteed, the compiler can put b wherever it wants.碰巧的是,在您的情况下, b存在于 a 之后a memory 中,但这并不能保证,编译器可以将b放在它想要的任何位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM