Thread: Pointers help please(using pointers to copy a string)

  1. #1
    Registered User
    Join Date
    Feb 2012
    Location
    Trinidad & Tobago
    Posts
    43

    Pointers help please(using pointers to copy a string)

    question A: in the while loop we have,"*pB++ = *pA++; " to copy the contents of strB to strB, why is the entire string copied because *ptrA++ insures that it starts from the second character in the string does it not?? please explain this.questionB:the size of strB is obviously to small to accept the contents of strA yet it does, ? can some one please explain why
    Code:
    #include char strA[80] = "A string to be used for demonstration purposes";char strB[1];int main(void){          char *pA;              // a pointer to type character           char *pB;              // another pointer to type character           puts(strA);            // show string A           pA = strA;             // point pA at string A */          puts(pA);              // show what pA is pointing to */          pB = strB;             // point pB at string B          putchar('\n');          while(*pA != '\0') {      //copies strA tp strB                 *pB++ = *pA++;          }         *pB = '\0';                   // adds the nul terminator to strB          puts(strB);           return 0;}

  2. #2
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    '*ptrA++ insures that it starts from the second character in the string does it not?' no it does not. the postfix ++ increments the pointer AFTER the assignment. but thats not your problem. you are just overwriting the memory that follows wherever strB is located. C doesn't protect from overwrites like that. you can happily corrupt memory all you want. you have to deal with the length of the destination string yourself, with a counter or something. look at the definitions of 'strcpy' and 'strncpy' to see an example.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 08-05-2011, 02:23 AM
  2. Pointers- Difference From Sending a Copy of the Object?
    By Shokwav in forum C++ Programming
    Replies: 7
    Last Post: 05-31-2011, 01:28 PM
  3. Replies: 2
    Last Post: 11-17-2010, 08:18 AM
  4. Replies: 5
    Last Post: 12-09-2008, 02:18 PM
  5. string pointers
    By studentc in forum C Programming
    Replies: 1
    Last Post: 05-14-2004, 09:53 AM