简体   繁体   English

使用指针将一个字符串复制到另一个字符串的程序不产生任何输出

[英]Program which copies one string to another using pointers produces no output

I wrote following piece of code which copies from one string to another using pointers. 我编写了以下代码,这些代码使用指针将一个字符串复制到另一个字符串。

#include<stdio.h> 

int main() { 

    char strA[80] = "A string to be used for demonstration purposes"; 
    char strB[80]; 
    char *ptrA; 
    char *ptrB; 
    ptrA = strA; 
    ptrB = strB;
    puts(ptrA);
    while(*ptrA != '\0') { 
        *ptrB++ = *ptrA++;
    }
    *ptrB = '\0'; 
    puts(ptrB); // prints a new line. 
    return 0;

}

Why does puts(ptrB) print nothing but just a newline ? 为什么puts(ptrB)打印换行符,什么都不打印? However puts(ptrA) prints the value of strA . 但是puts(ptrA)打印的价值strA

After the loop, the two pointers ptrA and ptrB are now pointing to end of the string. 循环之后,两个指针ptrAptrB现在指向字符串的结尾。 Printing them is printing an empty string. 打印它们将打印一个空字符串。 The new line is added by puts() . 新行由puts()添加。

The reason ptrA prints the original string is because puts(ptrA); ptrA打印原始字符串的原因是因为puts(ptrA); is called before the loop. 在循环之前被调用。


To print the original string, either use puts(strB) , or, if you like, let ptrB points back: 要打印原始字符串,请使用puts(strB) ,或者根据需要让ptrB指向后:

*ptrB = '\0'
ptrB = strB;  //add this
puts(ptrB);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM