从scanf()读取源字符串后,字符串未获取复制

时间:2017-05-20 17:47:57

标签: c arrays pointers

#include<stdio.h>

int main(){
  char a[20],*p;
  p=a;
  printf("Enter the String");
  scanf("%s",p);
  printf("\n\n%s\n",p);
  printf("Copying the String\n");
  char b[20],*pp;
  pp=b;
  while((*pp++=*p++));
  printf("\n%s\n",pp);

}

此代码不会复制字符串。但是,如果我将b [20]更改为b [10],它将复制字符串的最后9个字符。顺便说一句,当我设置b [10]并且输入由空格组成时,它不会复制字符串。

编译器设置: 配置为: - prefix = / Library / Developer / CommandLineTools / usr --with-gxx-include-dir = / usr / include / c ++ / 4.2.1 Apple LLVM版本8.1.0(clang-802.0.42) 目标:x86_64-apple-darwin16.5.0 线程模型:posix InstalledDir:/ Library / Developer / CommandLineTools / usr / bin

1 个答案:

答案 0 :(得分:2)

后:

    while((*pp++=*p++));

pp指向字符串的结尾。你想要:

     printf("\n%s\n",b);