c - 指针 C 语言
问题描述
我从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
将字符从(using )复制到( using 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
这样,字符 fromString2
被一一复制到末尾String1
顺便说一句:请注意,该main
功能是不安全的,因为保留的内存太少String1
推荐阅读
- sql-server - 如何调整此查询以使存储过程更高效
- python - 导入函数并将其分配给变量
- c# - 您可以使用 VisualStateManager 将悬停行为应用于 XAML 网格吗?
- json - 编辑大型 JSON 文件
- xamarin - CustomRenderer 动态改变边框颜色
- sql - 如何使用同一列创建数据透视查询
- python - Matplotlib 动态绘图
- sql-server - 两个独立的 TRUE SQL 语句组合成 FALSE
- java - 如何使用 SSL 使用 Spring Batch 访问 MongoDB
- c# - Visual Studio 2017 - 消息过滤器指示应用程序正忙