V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Mgzsnothing
V2EX  ›  C

求助 C 中的一个小问题

  •  
  •   Mgzsnothing · 2018-09-19 18:51:02 +08:00 · 1849 次点击
    这是一个创建于 2018 天前的主题,其中的信息可能已经有所发展或是发生改变。
    #include <stdio.h>
    #include <curses.h>
    
    int main()
    {
            void copy_string(char from[], char to[]);
            char a[] = "I am a teacher";
            char b[] = "you my student";
            char * from = a, * to = b;
            printf("string a = %s\n string b = %s\n",a,b);
            printf("\ncopy string a to string b:\n");
            copy_string(from, to);
            printf("string a = %s\nstring b = %s\n",a,b);
            return 0;
    }
    
    void copy_string(char from[],char to[])
    {
            int i = 0;
            while(from[i]!='\0')
            {
                    to[i++]=from[i++];
            }
            to[i]='\0';
    }
    

    第一段输出结果为:

    string a = I am a teacher
    string b = you my student

    copy string a to string b:
    string a = I am a teacher
    string b = om aytsauhert

    #include <stdio.h>
    #include <curses.h>
    
    int main()
    {
            void copy_string(char from[], char to[]);
            char a[] = "I am a teacher";
            char b[] = "you my student";
            char * from = a, * to = b;
            printf("string a = %s\n string b = %s\n",a,b);
            printf("\ncopy string a to string b:\n");
            copy_string(from, to);
            printf("string a = %s\nstring b = %s\n",a,b);
            return 0;
    }
    
    void copy_string(char from[],char to[])
    {
            int i = 0;
            while(from[i]!='\0')
            {
                    to[i]=from[i];
                    i++;
            }
            to[i]='\0';
    }
    

    想请教的问题是:

          to[i]=from[i];
          i++;
    

    改成了

          to[i++]=from[i++];
    

    之后为什么结果是不对的?

    whoami9894
        1
    whoami9894  
       2018-09-19 19:01:53 +08:00 via Android   ❤️ 1
    to[i++] = from[i++]
    一次迭代中 i += 2
    whoami9894
        2
    whoami9894  
       2018-09-19 19:03:20 +08:00 via Android
    如果这样写你需要给两个数组分别分配指针,然后 to[i++] = from[j++]
    SupperMary
        3
    SupperMary  
       2018-09-19 19:09:16 +08:00 via Android   ❤️ 1
    每次运行 to[i++]=from[i++],i 都加了两次。
    Mgzsnothing
        4
    Mgzsnothing  
    OP
       2018-09-19 19:17:00 +08:00
    @whoami9894 感觉自己问了个智障问题...多谢了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2856 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 13:13 · PVG 21:13 · LAX 06:13 · JFK 09:13
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.