2

Newbie Question: Hi! Intended to study how one array populates another (initialised) array during copying. So I ran the following bit of code.

#include<stdio.h>

char strA[]= "\nThis is array 'a'.\n";
char strB[] = "ABCDEFGABCDEFGABCDEFG";

int main()
{
  /* Copy one string to another using pointers */

  char *pA, *pB;
  puts(strA);
  puts(strB);
  pA=strA;
  pB=strB;
  puts(pA);
  puts(pB);
  while(*pA!='\0') {
    *pB++ = *pA++;
    puts(pB);
  }
  *pB='\0';
  puts(strB);

  return 0;
}

What I expected was to see how strA[] copied itself into strB[] at each step i.e. somewhere in the middle strB[] would have strA[] elements copied and remaining strB[] elements. But I could not find strA[] elements copied into strB[], though strB[] elements kept decreasing. The following is the output:

This is array 'a'.

ABCDEFGABCDEFGABCDEFG

This is array 'a'.

ABCDEFGABCDEFGABCDEFG
BCDEFGABCDEFGABCDEFG
CDEFGABCDEFGABCDEFG
DEFGABCDEFGABCDEFG
EFGABCDEFGABCDEFG
FGABCDEFGABCDEFG
GABCDEFGABCDEFG
ABCDEFGABCDEFG
BCDEFGABCDEFG
CDEFGABCDEFG
DEFGABCDEFG
EFGABCDEFG
FGABCDEFG
GABCDEFG
ABCDEFG
BCDEFG
CDEFG
DEFG
EFG
FG
G

This is array 'a'.

Process returned 0 (0x0)   execution time : 0.025 s
Press any key to continue.    

Am I missing something basic here? Any explanations would be of great help.

2
  • 2
    pB advances through strB, thus puts(pB) will print the string from the current position. If you want to print the whole, partially overwritten string, call puts(strB) inside the loop. Commented Jul 31, 2015 at 10:43
  • 2
    You're advancing the pointer in your loop, towards the end of the string. As you're treating said pointer as the beginning of your string, you're effectively moving the beginning of your string backwards. Try using two separate pointers, one for printing, and one for looping. Commented Jul 31, 2015 at 10:43

2 Answers 2

5

Since you're incrementing pB before you call puts(pB) in the loop, you're only seeing the part of strB starting from the current value of pB.

Change your loop to:

while(*pA!='\0') {
    *pB++ = *pA++;
    puts(strB);
}

and you'll see the entire string with the intermediate changes after each step.

Sign up to request clarification or add additional context in comments.

Comments

0

You are increment pB pointer before printing pB. Could you modify your while like below?

while(*pA!='\0') {

    *pB = *pA++;

    puts(pB);

    pB++;

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.