Thread: Returning a string...

  1. #1
    Registered User Vber's Avatar
    Join Date
    Nov 2002

    Returning a string...

    It is possible to return a String from a function?
    If yes, how?

    I'am trying to return a full string from this function:
    char substr(char *str, int start, int end)
        int i,j;
        char strCp[100];
        for(i = start, j = 0; i <= end; i++,j++)
            strCp[j] = str[i];
        strCp[j] = '\0';
        return *strCp;
    But this dont work... he just returns 1 char, not all the string.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    To return a string, make the return type char *. But in this case it won't work because your string is local, when the function returns it goes away so a pointer to it is invalid.

    My best code is written with the delete key.

  3. #3
    Registered User Vber's Avatar
    Join Date
    Nov 2002

    So, no way to solve my problem here?

    Hmm, just assigning to an global variable the value of my local variable? or this isnt good too?

  4. #4
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    You could strcpy() your local string to a global one if you wanted, in which case you wouldn't have to return it. However, use of global variables should be kept to a minimum.

    It is better to pass the function a pointer to a pre-allocated buffer, along with the size of the buffer. The function can then write data directly to it.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  5. #5
    Registered User Vber's Avatar
    Join Date
    Nov 2002

    Ok, I got it :)

    Thanks for the help

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Please check my C++
    By csonx_p in forum C++ Programming
    Replies: 263
    Last Post: 07-24-2008, 09:20 AM
  2. Compile Error that i dont understand
    By bobthebullet990 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 09:19 AM
  3. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM