首页 > 解决方案 > 指针 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
   } 
}

标签: cpointers

解决方案


这个函数有什么作用?

它连接两个字符串,即它的作用与标准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;
} 

将指针移动s1String1. 所以你有了

String1: Hello\0
               ^
               |
               s1

String2: World\0
         ^
         |
         s2

那么这部分

for (; *s1 = *s2; ++s1, ++s2) {
  ; // empty statement
} 

String2将字符从(using )复制到( using s2) 末尾。String1s1

一个循环后,您将拥有:

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


推荐阅读