Skip to main content
gamedev.net
🔒 Locked

Returning a Character Array?

Started by Peddler Oct 15, 2000 at 8:14 AM 14 replies 450+ views
Original Post
Peddler
Peddler
Hey, does anyone have any tips on how to easily return a character array from a function or class method?? I suppose I could encapsulate the character array into a struct and then return the struct, but is there 'correct' way of returning an array?
    
//definition

char[] ReturnCharArray(void);

//implementation

char[] ReturnCharArray()
{
  char SomeArray[256]; //

  strcpy(SomeArray, "TEST");

  return SomeArray;
}

//main program

char CharArray[256];

strcpy(CharArray, ReturnCharArray());
    
I know this doesn't work, but just though I would give an example as to what I want to do. Any help would be appreciated. -Tim Edited by - Peddler on 10/15/00 8:17:58 AM
jumble
jumble
Yes. Return a pointer to the char.

    

//definition

char * ReturnCharArray();

//implementation

char * ReturnCharArray()
{
char SomeArray[256];
strcpy (SomeArray, "TEST");
return SomeArray;
}

//main program


char CharArray[256];
strcpy(CharArray, ReturnCharArray());

jumble-----------
Syzygy
Syzygy
Ummm... I wouldn''t suggest returning a pointer to a local variable as jumble suggests. The problem is that a local variable (in this case "SomeArray") is created on the stack and only lives for the lifetime of the function "ReturnCharArray". This means that the "SomeArray" variable is gone once the ReturnCharArray function exits. However, the function returns a pointer to that local variable, so it''s used after the function exits, and therefore after the variable has been destroyed.
Now, this may actually work, and I verified that it does work in VC6 (although the compiler does warn you about "returning address of local variable or temporary"). However, it''s only working by sheer luck. The pointer being returned is into a section of the stack that is not really valid, but that happens to still contain the data that you care about.
So what is the correct way to do this? Here you go:
    
//definition

void FillCharArray(char *szData, int nCount);
//implementation

void FillCharArray(char *szData, int nCount) {
strncpy(szData, "TEST", nCount);
szData[nCount-1] = ''\0'';
}
//main program

char CharArray[256];
FillCharArray(CharArray, 256);

...Syzygy
Wilka
Wilka
using a static would work, but it means you need to remember to copy the char array before you do anything else cos any other function should call the function and change the array. The way you should probably do it is via an output parameter as Syzygy suggested, or put the array inside a class. An even better way would be to use the standard C++ string class (std::string). Using std::string or your own class (or std::vector&ltchar>) also means you don''t need to know how big the array needs to be.
djsteffey
djsteffey
    
char* returnArray()
{
char* temp = new char[size];
strcpy(temp, "whatever");
return temp;
}

void deleteArray(char* a)
{
if (a == NULL)
return;
delete [] a;
return;
}



you must remember to delete the memory after you are finished with it like using function number 2



"Now go away or I shall taunt you a second time"
- Monty Python and the Holy Grail
themGames Productions

Grib
Grib
quote:
Original post by ncsu121978

        

void deleteArray(char* a)
{
if (a == NULL)
return;
delete [] a;
return;
}



you must remember to delete the memory after you are finished with it like using function number 2
themGames Productions




Note, it''s ok nowadays to delete [] NULL; or delete NULL;
I assume the same is true for free.



djsteffey
djsteffey
i did forget one thing in the function deleteArray(char* a)
before you return
    
void deleteArray(char* a)
{
if (a == NULL)
return;
delete [] a;
a = NULL; // forgot to add this line

return;
}



"Now go away or I shall taunt you a second time"
- Monty Python and the Holy Grail
themGames Productions

Grib
Grib
quote:
Original post by ncsu121978

i did forget one thing in the function deleteArray(char* a)
before you return
        
void deleteArray(char* a)
{
if (a == NULL)
return;
delete [] a;
a = NULL; // forgot to add this line

return;
}



"Now go away or I shall taunt you a second time"
- Monty Python and the Holy Grail
themGames Productions




This is even more pointless, a is just a local variable, it does not change the param passed to it. Just use delete [] a;

a = new char[59];
in.read(a,59); // ok
deleteArray(a);
if(a!= NULL) cout << a << endl; // boom! undefined behaviour
// a != NULL

In a class you sometimes will set a member pointer to NULL after you delete. It''s just a convention to tell any future users of that variable that the variable is no longer valid. Some people put m_p = 0 in destructors, in the hope that anyone who might be using the object after it''s destructed will pick up on the hint and quit it.
Grib
Grib
quote:
Original post by Anonymous Poster

Wouldn''t you better doing this:

bool func (char *ReturnString)
{
strcpy (ReturnString, "HELLO");
return (true); // success
}


void main (void)
{
char str [80];

if (func (str))
printf (str);

}


THat way the calling code has control over the memory block, so it can be either a local varible or malloced memory.



Yep, though you may want to pass a size to your function.
char * func(char *buff, size_t s) {
strncpy(buff,"Hello",s);
return buff;
}

The other option is to use vector or string, This adds a lot of copying, but in the case of string it might not be too bad if your STL has copy on write.

string trim(const string &s) {
return s.substr(0,s.find_last_of(" /t/n/r"));
}

This could be as fast as two pointer assignments, though it could also allocate, make a full copy, allocate again make another copy. For trim("Hello "); it will make another copy for the temporary.

May your millage vary.
Shannon Barber
Shannon Barber
Peddler, are you using C or C++?

char[] is C syntax, though it does compile in C++...

char[] and char* are almost the same thing.
The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Peddler
Peddler
wow, thanks for all the responses guys. I put in jumbles and it seems to be working fine...though, I am going to play with all the other suggestions and see what I can do.

Magmai, I''m using c++..

thanks again
jumble
jumble
Yeah, sorry about that. Thanks for pointing out my mistakes

On second thoughts, you could get away with using a macro for it, this'll also mean you dont have the function call overhead:

        
#define fillarray(x) strcpy(x, "TEST");

//main program

char somearray[256];

fillarray(somearray);


Even though I suspect this isn't what you want, hey, it's a suggestion

Edited by - jumble on October 16, 2000 4:22:03 PM
jumble-----------
Wilka
Wilka
nooooooooooo!

not a macro!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.