Thread: Returning string from char *function()

  1. #1
    Registered User
    Join Date
    Aug 2008
    Location
    Finland
    Posts
    14

    Returning string from char *function()

    I am wondering why i have to use "helper" pointer a to get the s return right value.
    Why i cant do it directly with s?
    Code:
    char *copyn(char *s, const char *t, size_t n){
     char *a;
      a=s;
     while(*a!='\0')
         a++;
     for(; n>0; n--){
       *a++ = *t++;
     }
     *a++='\0';
    return s;
    }

  2. #2
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    Because you're modifying s (or a, in this example)?

    Every time you do "a++" you're changing the value of a. It no longer points to the beginning of the string. Thus when you return it, you're returning a pointer to the end (actually, one past the end) of the string. That's why you keep a spare pointer to the beginning of the string. Otherwise how would you return the proper value?

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Have you read the code?
    Have you understood the code?
    Have you tracked the value of 's' and 'a' as the function executes?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Aug 2008
    Location
    Finland
    Posts
    14
    Quote Originally Posted by cas View Post
    Because you're modifying s (or a, in this example)?

    Every time you do "a++" you're changing the value of a. It no longer points to the beginning of the string. Thus when you return it, you're returning a pointer to the end (actually, one past the end) of the string. That's why you keep a spare pointer to the beginning of the string. Otherwise how would you return the proper value?
    Thanks cas
    That really didnīt come up in my mind...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  2. String Manipulation problems -_-
    By Astra in forum C Programming
    Replies: 5
    Last Post: 12-13-2006, 05:48 PM
  3. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 11:03 PM
  4. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  5. String sorthing, file opening and saving.
    By j0hnb in forum C Programming
    Replies: 9
    Last Post: 01-23-2003, 01:18 AM