?
Solved

Returning a character array

Posted on 2003-02-28
20
Medium Priority
?
377 Views
Last Modified: 2013-12-14
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
Comment
Question by:blaksaga
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 3
  • 2
  • +4
20 Comments
 

Accepted Solution

by:
entropy12 earned 100 total points
ID: 8045256
#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
 
LVL 8

Expert Comment

by:Exceter
ID: 8045388
>> 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
 
LVL 8

Expert Comment

by:Exceter
ID: 8045394
>> while(1);

What is this for? The program will never terminate!

Exceter
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Expert Comment

by:entropy12
ID: 8045460
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
 
LVL 2

Expert Comment

by:BorlandMan
ID: 8045982

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
 
LVL 8

Expert Comment

by:Exceter
ID: 8046066
>> 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
 
LVL 8

Expert Comment

by:Exceter
ID: 8046071
>> about the memory leak: i feel ashamed.

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

Exceter
0
 
LVL 2

Expert Comment

by:BorlandMan
ID: 8046517

>> ch=getch()

yep.

>> system("pause")

ah good one.

thx,
J
0
 
LVL 6

Expert Comment

by:PlanetCpp
ID: 8046745
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
 
LVL 8

Expert Comment

by:Exceter
ID: 8047512
>> 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
 
LVL 6

Expert Comment

by:Mafalda
ID: 8047517
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
 
LVL 8

Expert Comment

by:Exceter
ID: 8047530
>> 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
 
LVL 6

Expert Comment

by:Mafalda
ID: 8047804
Exceter,
1) You are right.
2) blaksaga might be unaware of STL.
3) It is simple.
0
 
LVL 6

Expert Comment

by:PlanetCpp
ID: 8048672
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
 
LVL 8

Expert Comment

by:Exceter
ID: 8048802
>> 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
 
LVL 30

Expert Comment

by:Mayank S
ID: 8108925
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
 
LVL 8

Expert Comment

by:Exceter
ID: 8114328
>> 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
 
LVL 6

Expert Comment

by:PlanetCpp
ID: 8116337
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
 

Author Comment

by:blaksaga
ID: 8420921
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
 
LVL 8

Expert Comment

by:Exceter
ID: 8421118
>> 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
THe viewer will learn how to use NetBeans IDE 8.0 for Windows to perform CRUD operations on a MySql database.
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
Suggested Courses

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question