学习 C 指针我无法弄清楚为什么这不起作用(K&R 练习 5-2)

Learning C pointers i cant figure out why this is not working (K&R excercise 5-2)

好的,所以我实际上正在阅读 K&R C 书(我知道它很旧并且有很多过时的东西,特别是在安全方面,但我只是想做练习)我一直在练习5-2 我需要用指针实现我自己的 strcat。我的代码如下:

#include <stdio.h>
#include <stdlib.h>

char *Strcat(char *string1, const char *string2);

int main(void){
  char string1[100]="hello";
  char string2[100]="1234";
  printf("%s",Strcat(string1,string2));
  return 0;
}

char *Strcat (char *string1, const char *string2){
    int i=0;
    char *temp=string1;
    while(*string1){// move the pointer to find the end of the string
     ++string1;
    }
    while(*string1++=*string2++)//copy string 2 at the end of string 1
     ;
    puts(string1);//print string 1 concatenated with string 2
    return temp;//send back temp pointing to string1 for printing
}

我的问题是,为什么如果我尝试在函数内打印 string1,它只会打印空白?它不应该打印整个字符串吗?如果我打印 temp 它很好,因为它运行打印函数直到它找到 '\0' 但是当尝试使用字符串 1 时它似乎位于 '\0' 指针不应该回到 string1[0] 位置吗?这可能很简单,但我不明白为什么会这样...

感谢任何帮助!谢谢!!!

++string1 对变量的影响等同于 string1 = string1 + 1。因此,当您尝试打印 string1 时,它不再指向原始字符串的开头。

字符串未指向数组的开头。由于增量操作。

正如 kaylum 指出的那样,您丢失了指针 string1。在开始时,您分配了一个临时指针 temp 来保存原始 string1 位置 - 这就是您需要在 Strcat 函数中的 puts 函数中使用的内容。

puts(temp);

对了,这三行

while(*string1){// move the pointer to find the end of the string
 ++string1;
}

可以写成一行:

while( *string1++ );