【问题标题】:Learning C pointers i cant figure out why this is not working (K&R excercise 5-2)学习 C 指针我无法弄清楚为什么这不起作用(K&R 练习 5-2)
【发布时间】: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 的用途

标签: c pointers strcat


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    puts(temp);
    

    顺便说一下,这三行

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

    可以写成一行:

    while( *string1++ );
    

    【讨论】:

    • 感谢artm!是的,你是对的!暂时不需要多余的线,感谢您的观察! :)
    • while( *string1++ ); :再算一次(过去的'\0'
    【解决方案3】:

    string 未指向数组的开头。由于增量操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多