C 为什么';下面的程序不能将同一字符串打印两次吗?

C 为什么';下面的程序不能将同一字符串打印两次吗?,c,C,我不明白为什么不能打印同一个字符串两次。 下面是示例代码 int main(void) { char *source = "duplicate message"; char *p1,*p2,destination[50]; p1 = source; puts(p1); p2=destination; while(*p2++ =*p1++) ; puts(p2); return 0; } 在循环结束时,您

我不明白为什么不能打印同一个字符串两次。 下面是示例代码

int main(void)
{
    char *source = "duplicate message";
    char *p1,*p2,destination[50];


    p1 = source;
    puts(p1);
    p2=destination;  
    while(*p2++ =*p1++)
          ;
    puts(p2);
    return 0;
}

在循环结束时,您的
p2
指向
目的地
字符串的末尾<代码>目的地此时确实包含
的副本。但是您的
p2
没有指向
目的地的开头。它指向存储在
destination
中的复制字符串的末尾。即,
p2
指向空字符串。这就是您的第二个
放置的
打印的内容-一个空字符串

如果您想打印
目的地
字符串,这正是您应该在代码中写入的内容-
放置(目的地)
。为什么您决定将其表示为
put(p2)


如果你想用它进行实验,你可以让你的
p2
在循环结束后指向
目的地的不同位置。如果将其指向
目的地的开头
put(p2)
将打印整个
目的地
字符串。如果将其指向
目的地
字符串的中间,则
put(p2)
将打印类似于
“ate消息”
等内容。

此代码可能对您有所帮助:

char *my_strcpy(char dest[], const char source[])
{
  int i = 0;
  while (source[i] != '\0')
  {
    dest[i] = source[i];
    i++;
  }
  dest[i] = '\0';
  return(dest);
}

请注意源代码的
常量,这表示函数无论如何都不能更改源字符串。

另一个注意事项。与将
增量后
赋值
打包到
while测试子句中
后面紧跟着一个
空行
,您可以通过实际使用
while
赋值
下的行,使代码更具可读性。您还必须注意
null终止
所有字符串。当您学习指针时,只需拿出铅笔和纸,画出字符串表示,并手动遵循循环逻辑,确认循环已完成您所需的所有操作,这通常很有用:

#include <stdio.h>

int main(void)
{
    char *source = "duplicate message";
    char *p1,*p2,destination[50];

    p1 = source;
    puts(p1);

    p2=destination;  

    while (*p1)         /* to walk down string, *p evaluates true until '\0' */
        *p2++ = *p1++;  /* dereference pointer, assign, post-increment       */

    p2++;               /* increment pointer to next memory location         */
    *p2 = 0;            /* null-terminate the string                         */

    p2 = destination;   /* reset pointer to beginning of destination         */

    puts (p2);

    return 0;
}

您没有为其他指针分配内存。因为当
while
循环完成时,
p2
不再指向
目标的开始。它指向字符串的末尾。第二次你什么也得不到。尝试
put(destination)
而不是
put(p2)
,或者尝试
p2=destination;放置(p2)
(将
p2
重新分配到
目的地的开头)。
$./bin/dest
duplicate message
duplicate message