微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

指针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(使用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保留的内存太少了

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。