使用指针扫描和打印字符串

Scanning and printing strings using pointers

我编写了一段代码,用于使用指针从用户那里扫描一个字符串并将其存储在另一个字符串数组中并打印该字符串数组。输出变得很奇怪。打印前三个字符,但接下来的字符作为随机垃圾值出现。请告诉我代码中的错误。以下是代码:

#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='[=10=]';
    p1=&str1[0];
    while(*p1)
        *p2++=*p1++;
    *p2='[=10=]';
    printf("The copied string is :");
    p2=&str2[0];
    while(*p2)
        printf("%c",*p2++);
}

没有将终止空字符('[=11=]') 放在字符串str1[]str2[] 的末尾。并且您正在 尝试取消引用并检查第一个 while 循环条件中未初始化的值 while(*p1)

printf("Enter a string\n");

do{
 scanf("%c",p1++);
}while(*(p1 - 1) != '\n'); //try the do while loop

*(p1 - 1) = '[=10=]';          //placing terminating null character

p1 = &str1[0];
while(*p1){
    *p2++ = *p1++;
}
*p2 = '[=10=]';                 //placing terminating null character

这里是演示代码:https://ideone.com/dF2QsJ

Why have you checked the condition for the new line in the do while condition? And why p1-1?

这是因为您通过输入 '\n' 来结束输入,该 '\n' 存储在 p1,然后 p1 在每次迭代结束时移动到 p1 + 1。所以,我检查 '\n' 是否存在于 p1 - 1.

好的, 为什么不使用 %s 并直接获取输入。您可以获得整个字符串,而不是遍历每个字符。

这个循环

while(*p1)
    scanf("%c",p1++);

str1 存储任何内容之前检查 str1 的内容(由 p1 指向)。未初始化的内存可能包含任何内容,因此此循环可能永远不会执行(如果第一个字符恰好为 NUL),或者可能 运行 超出数组的末尾(损坏内存)。