【发布时间】:2016-10-19 01:53:44
【问题描述】:
好的,所以我实际上正在阅读 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。您丢失了原始字符串的开头。 -
嗨凯勒姆!感谢您的快速回复!我明白了,所以这就是我的想法,不知何故,我的脑海里一直在想,神奇的函数 puts 会将指针发送回 string1 的开头,但没有办法知道是有道理的,因为现在它认为 string1 从那个开始定位我移动它。再次感谢! :D
-
改用
puts(temp);,这就是 temp 的用途