问题描述
我从Deitel的书中举了这个例子。您能解释一下string1如何存储整个字符串吗?
#include <stdio.h>
#define SIZE 80
void mystery1(char *s1,const char *s2); // prototype
int main(void)
{
char string1[SIZE]; // create char array
char string2[SIZE]; // create char array
puts("Enter two strings: ");
scanf("%79s%79s",string1,string2);
mystery1(string1,string2);
printf("%s",string2);
}
// What does this function do?
void mystery1(char *s1,const char *s2)
{
while (*s1 != '\0') {
++s1;
}
for (; *s1 = *s2; ++s1,++s2) {
; // empty statement
}
}
解决方法
此功能做什么?
它连接两个字符串,即与标准strcat
函数的作用相同。参见https://man7.org/linux/man-pages/man3/strcat.3.html
假设输入为“ Hello World”。
仅在调用该函数时,它在内存中的某些位置看起来就像:
String1: Hello\0
^
|
s1
String2: World\0
^
|
s2
现在这部分
while (*s1 != '\0') {
++s1;
}
将指针s1
移动到String1
的末尾。所以你有
String1: Hello\0
^
|
s1
String2: World\0
^
|
s2
然后这部分
for (; *s1 = *s2; ++s1,++s2) {
; // empty statement
}
将字符从String2
(使用s2
)复制到String1
(使用s1
)的末尾。
一个循环后,您将拥有:
String1: HelloWorldW
^
|
s1
String2: World\0
^
|
s2
再循环一次,您将拥有:
String1: HelloWorldWo
^
|
s1
String2: World\0
^
|
s2
以此类推。
最后,您将拥有
String1: HelloWorld\0
^
|
s1
String2: World\0
^
|
s2
最终结果:String2
已连接到String1
关于for (; *s1 = *s2; ++s1,++s2) {
The ; says: no initialization needed
The *s1 = *s2; says: Copy the char that s2 points to to the memory that s1 points to.
Further,it serves as "end-of-loop" condition,i.e. the loop will end when a \0 has
been copied
The ++s1,++s2 says: Increment both pointers
通过这种方式,String2
中的字符被一一复制到String1
的末尾
顺便说一句:注意main
函数是不安全的,因为为String1
保留的内存太少了