Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6
  1. #1
    jkd
    jkd is offline
    Senior Coder jkd's Avatar
    Join Date
    May 2002
    Location
    metro DC
    Posts
    3,163
    Thanks
    1
    Thanked 18 Times in 18 Posts

    returning char[] ?

    I'm learning C++, and am unable to do:

    char[] someFunction(sometype somearg) {
    // bla
    }

    inside the function, I return "a string literal". I suppose it is because it wants to return a reference to it? I've resorted to the apstring class, but would like to be able to use C-strings...

  • #2
    Regular Coder
    Join Date
    Jul 2002
    Location
    Kentucky
    Posts
    133
    Thanks
    0
    Thanked 1 Time in 1 Post
    Are you actually declaring the function like this?:

    char[] someFunction(sometype somearg)

    If so, are you getting an error from the compiler that says something like "parse error before ["? Try declaring your function without the brackets. I may be wrong, but I'm not able to declare and define a function with char[], but I can with char.

    Hope this helps.

    Smeagol

  • #3
    New Coder
    Join Date
    Sep 2002
    Location
    Up North (UK)
    Posts
    46
    Thanks
    0
    Thanked 0 Times in 0 Posts
    jkd,

    Can you not declare it as:

    Code:
    char* someFunction(sometype somearg)

  • #4
    Regular Coder
    Join Date
    Jul 2002
    Location
    Belgium
    Posts
    124
    Thanks
    0
    Thanked 0 Times in 0 Posts
    you have to declare it as a pointer.
    Code:
    char * function ();
    
    int main()
    {
    	char test[100];
    	sprintf(test,"%s",function());
    	printf("%s",test);
    	return 0;
    }
    
    char * function ()
    {
    	static char str[100];
    	strcpy(str,"testing the return of a string");
      return str;
    }
    the static in the function is there so that the pointer will not be destroyed when the function returns

    I hope this helps you a bit

  • #5
    Regular Coder
    Join Date
    Jul 2002
    Location
    Belgium
    Posts
    124
    Thanks
    0
    Thanked 0 Times in 0 Posts
    damn too late

  • #6
    jkd
    jkd is offline
    Senior Coder jkd's Avatar
    Join Date
    May 2002
    Location
    metro DC
    Posts
    3,163
    Thanks
    1
    Thanked 18 Times in 18 Posts
    That's cool, thank you.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •