Shanthan K Shanthan K -4 years ago 92
C Question

String is not getting Copied, after reading the source string from scanf()

#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);

}


This code is not copying Strings. However, If I change b[20] to b[10], it's copying last 9 characters of a String. By the way, when I set b[10] and if the input consists of a space then it is not copying the strings.

Compiler Setup:
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin16.5.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

Answer Source

After:

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

pp is pointing to the end of the string. You want:

     printf("\n%s\n",b);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download