Search code examples
cstringpointersputs

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 ? However puts(ptrA) prints the value of strA.


Solution

  • After the loop, the two pointers ptrA and ptrB are now pointing to end of the string. Printing them is printing an empty string. The new line is added by puts().

    The reason ptrA prints the original string is because puts(ptrA); is called before the loop.


    To print the original string, either use puts(strB), or, if you like, let ptrB points back:

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