DR. SABUZ
DR. SABUZ

Reputation: 19

Why pointer in puts() function isn't work in line 4 of the following code? Though line 1 is working

char poem[80]="Amar sonar bangla";
char rpoem[80];
int main()
   {
      char *pA, *pB;
      pA=poem;
      puts(pA);  /*line 1*/
      puts(poem);/*line 2*/
      pB=rpoem;
      while(*pA!='\0')
        {
          *pB++=*pA++ ;   
        }
     *pB='\0';
     puts(rpoem);/*line 3*/
     puts(pB);   /*line 4*/

    return 0;
  }

When I run this code, it shows results only for puts(pA), puts(poem) and puts(rpoem) but no results for puts(pB). I correctly assigned pB to pointer rpoem. After coping the string from poem to rpoem that is *pA to *pB. But in puts() function pB isn't show the copied string. Would someone please tell me the fault?

Upvotes: 1

Views: 40

Answers (2)

Mohit Prakash
Mohit Prakash

Reputation: 512

Because pB pointer is assigned by null value which replaced to previous value of pB pointer. So line 4 print null value.

Upvotes: 0

P.P
P.P

Reputation: 121357

Because at "line 4", 'pB' is pointing at the NUL byte, not at the beginning of the string. You can use a temp pointer in the loop instead of directly modifying 'pB' directly.

Upvotes: 1

Related Questions