I wrote a code for scanning a string from user using pointers and storing it in another string array and printing that string array. The output is coming quite strange. The first three characters are printed but next characters are coming as random garbage values. Please tell me the error in the code. Following is the code:
#include<stdio.h>
int main(void)
{
char str1[8];
char *p1=str1;
char str2[8];
char *p2=str2;
printf("Enter a string\n");
while(*p1)
scanf("%c",p1++);
*p1='\0';
p1=&str1[0];
while(*p1)
*p2++=*p1++;
*p2='\0';
printf("The copied string is :");
p2=&str2[0];
while(*p2)
printf("%c",*p2++);
}
You are not placing the terminating null character ( '\\0'
) at the end of your strings str1[]
and str2[]
. And you are trying to dereference and check the value which is not initialized in your first while loop condition: while(*p1)
printf("Enter a string\n");
do{
scanf("%c",p1++);
}while(*(p1 - 1) != '\n'); //try the do while loop
*(p1 - 1) = '\0'; //placing terminating null character
p1 = &str1[0];
while(*p1){
*p2++ = *p1++;
}
*p2 = '\0'; //placing terminating null character
here's the demo code: https://ideone.com/dF2QsJ
Why have you checked the condition for the new line in the do while condition? And why
p1-1
?
This is because you end the input by entering a '\\n'
which gets stored at p1
and then p1
moves to p1 + 1
at the end of each iteration. So, I check whether a '\\n'
is present at p1 - 1
.
okay, Why arent you using %s and get the input directly. you can get the entire string rather than looping over each character.
This loop
while(*p1)
scanf("%c",p1++);
checks the contents of str1
(pointed at by p1
) before ever storing anything there. That uninitialized memory might contain anything, so this loop might never execute (if the first char happens to be NUL), or might run off the end of the array (corrupting memory).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.