• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 378
  • Last Modified:

Returning a character array

Can somebody write me a simple function that returns a character array?  This is what I tried to use but it wouldn't work:

char * site::getdomain(){
 return domain;
}

I need it to return the char array of "x.domain".
0
blaksaga
Asked:
blaksaga
  • 9
  • 3
  • 2
  • +4
1 Solution
 
entropy12Commented:
#include <iostream>
using namespace std;

char* testdd(char a, char b)
{
     char* test = new char[1];
     test[0] = a;
     test[1] = b;
     return test;
}


int main(int argc, char *argv[])
{
     char* test = testdd('a','b');
     cout<<test[0]<<test[1];

while(1);

}
0
 
ExceterCommented:
>> Can somebody write me a simple function that returns a character array?

Arrays cannot be passed/returned by value and therefore, they cannot be returned. You can pass/return pointers to an array however. For example,

char* test( char* s )
{
    strcpy( s, "Testing..." );
    return s;
}

this can be called by saying,

char str[25];
char* temp = test( str );
cout << temp << endl;

-- output --

Testing...

Note: entropy12, that code has a memory leak because you do not free the memory you allocate inside testadd().

Exceter
0
 
ExceterCommented:
>> while(1);

What is this for? The program will never terminate!

Exceter
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
entropy12Commented:
while(1) is just something i use in dev-c++ to get the dos window to stay open indefinitely.

about the memory leak: i feel ashamed. i guess i've been programming in c# for too long
0
 
BorlandManCommented:

At least you are trying to help out right?
C# eh... cool.

one way you can keep the dos window open is to use

ch = getch();  the window will not close until you press a key.


hth
J
0
 
ExceterCommented:
>> ch = getch();  

You don't even need to say that because you do not have to capture a return value. You can simply say,

getch();

Or, better yet,

system("pause");

this displays a press any key message and then waits for you to do so.

Exceter
0
 
ExceterCommented:
>> about the memory leak: i feel ashamed.

It happens to all of us from time to time. :-)

Exceter
0
 
BorlandManCommented:

>> ch=getch()

yep.

>> system("pause")

ah good one.

thx,
J
0
 
PlanetCppCommented:
only way to return a char array from a function is to have the char array thats inside the function be static, i don;t thik this is good practice but it's perfectlly legal. the char array won't be in the local stack of the function and will last as long as the program runs

char* ThisIsBadPracticeThough()
{
static char DontSayImEncouragingThis[50] = {"hello world"};
return DontSayImEncouragingThis;
}

but you realy should never return it unless its the same pointer passed by reference but in that case your changing it anyway...might as well just use the return type for a success/fail indictor
0
 
ExceterCommented:
>> only way to return a char array from a function is to have the char array thats inside the function be static,

Arrays cannot be passed by value. You are simply returning a pointer to a static array. Also, this is not the only way to do this. It can be done at least three ways to return a pointer to a char array from a function, for example,

char* test1( char* s )
{
    return s;
}

char* test2()
{
    static char s[] = "hello world";
    return s; // As PlanetCpp pointed out
}

char* test3()
{
    return new char[25];
}

Note: You must remember to free the memory allocated inside test3 when you are done with it or you will have a memory leak.

Exceter
0
 
MafaldaCommented:
If you use a std::vector<char> or a std::string you can return them by value and ease the usage.

e.g.

string site::getdomain(){
return domain;
}

to get a const char * use c_str()
e.g.

site s;
call_a_function_with_a_char_array(s.getdomain().c_str());

to use these you will need to include and declare usage as follow
#include <string>
using std::string;

#include <vector>
using std::vector;

or instead of all the std::string, std::vector et. use a namespace usage:

using namespace std;

this is problematic if you already use "using namespace xxxx" in your program.
0
 
ExceterCommented:
>> If you use a std::vector<char> or a std::string you can return them by value and ease the usage.

Yeah, objects can be passed by value. However, the question was, "...simple function that returns a character array?" and as we both know, character arrays cannot be passed to or returned from a function. Only their pointers can be passed/returned.

Exceter
0
 
MafaldaCommented:
Exceter,
1) You are right.
2) blaksaga might be unaware of STL.
3) It is simple.
0
 
PlanetCppCommented:
exeter what i said was the only way to return it was for the one inside to be static, the way test2 uses.
test1 is a pass through, your passing the array (and yes im aware they are by reference) changing it then passing the pointer back out, it's almost redundant to do that.
and test3 is legal yes but REALLY  a bad idea. what if you made a class and used that method, you can trust the user to remember to delete the pointer?
thats a memory leak waiting to happen.
0
 
ExceterCommented:
>> exeter what i said was the only way to return it was for the one inside to be static, the way test2 uses.

Yes, I am not disputing what you said. I am simply telling you that char arrays CANNOT be returned. Their pointers can be passed/returned but no more.

>> test1 is a pass through, your passing the array (and yes im aware they are by reference) changing it then passing the pointer back out, it's
>> almost redundant to do that.

Yes it is a pass through, but it was only a demonstration. Also, it is not a redundant thing to do in certain situations. For example, suppose you wanted to write a function that converted the text in a char array to upper case. Further suppose that, although it is by no means necessary, you wanted to call it from within a stream. For example,

char name[] = "Exceter";

cout << strtoupper( name );

You could not do this unless you returned the same pointer the function was passed, or unless you allocated memory and returned that pointer, which as you have already pointed out is a rather trusting thing to do.

>> and test3 is legal yes but REALLY  a bad idea. what if you made a class and used that method, you can trust the user to remember to
>> delete the pointer?
>> thats a memory leak waiting to happen.

That is true. However, this to can have practical uses if handled properly. Suppose you wanted to write a simple dynamic stack. I can think of at least two ways you can dynamicly manage the memory. First, you can simply use an array as the stack. When you need more memory you can simply declare a temporary array and copy the stack into it. You then delete the stack, allocate a larger chunk of memory, copy the temporary array back into the stack, and delete the temporary array. Second, you can create a structure that contains a data member and a pointer that can be set to the previous element in the stack. When you call push() it allocates more space and sets the pointer to the address of the previous node. pop() would in like manner delete each node as it popped the values off the stack. Both push() and pop() would return the pointer to the current element in the stack. If there were any elements left over the class destructor would finish the job of freeing the memory.

I only used those examples to demonstrate that character arrays CANNOT be passed to, nor returned from a function. In all three examples the common thread is that the pointers are all that is passed/returned. Nothing more and nothing less. It is totally irrelevant where the memory is allocated or why it was allocated or even if its allocation was a good idea. The fact reamins that the pointer was passed/returned and not the array.

Exceter
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Don't ever try returning a local array from a function because once the function finishes execution, its activation record is popped off the stack and the returned address will now be free. So, it'll be a dangling reference problem. You can try returning a string which is a class-member, from one method of the class to another, 'coz at least the string member will live as long as the object will live.

Mayank.
0
 
ExceterCommented:
>> Don't ever try returning a local array from a function because once the function finishes execution, its activation record is popped off the stack
>> and the returned address will now be free. So, it'll be a dangling reference problem.

You are assuming that the array declared inside the function is on the stack. If the array is allocated dynamicly, I.E. operators new/delete or the functions malloc/free, then the array resides on the heap and will remain there until it is deleted be that through the usage of the delete operator or the program exiting(On modern OSs anyway).

Exceter
0
 
PlanetCppCommented:
blaksaga you have to pick an answer or else this will go on forever and i will get emails forever.. :o\
or tell why current answers are no good
or ask moderators to delete...
or something,,anything
0
 
blaksagaAuthor Commented:
Heh, sorry...I forgot to accept an answer.  I am just going to accept the first decent answer provided since there are so frickin many of them.  Thanks all for your help!
0
 
ExceterCommented:
>> I am just going to accept the first decent answer provided...

Would you be so kind as to define "descent" for me? If you mean that you accepted the first working answer then entropy12's initial post is the logical choice. However, as I recall there were several problems with the first solution, namely that it had a memory leak.

I beleive that I fully answered the question with both adequate examples and explanations as to how and why arrays are passed/returned by reference and not by value. However, what's done is done. I would mearly ask that you put more thought into which answer you accept in the future...

Exceter
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 9
  • 3
  • 2
  • +4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now