473,320 Members | 1,840 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

basic question about returning strings / char arrays

Hi everybody, have a quick look at this code:

=====
=====

int main(void) {

string msg;
makeString(msg);
cout << "back in main, result = " << msg << endl;
return EXIT_SUCCESS;
}

void makeString(string& message){
char theMessage[25] = "Here is a char array";
message = theMessage;
cout << "insdie the makeString func,theMesage = '" << message <<
endl;
}

=====
=====

I would like to write functions that return strings that i can simply
assign to a string (or char*) from my calling function. The above
code achieves the result i want, but it looks a bit strange to me (I
have a java background). I would prefer the makeString function to
return the string, instead of adjusting a reference to a string that
is passed to it. I would rather it not take a variable at all.

The problem i have found is that making the string in the makeString()
function, then returning it does not work because the stackframe for
that function is destroyed when the function ends, so referencing a
tring variable in there makes no sense. I could make a string on the
heap and return a pointer to it, but then do i have manage freeing up
space for that string when i'm done using it in the calling mfunction?
this seems like a lot of extra work.

thank you for any advice.
Jun 27 '08 #1
8 2167
darren wrote:
Hi everybody, have a quick look at this code:

=====
=====

int main(void) {
Ugh... Drop the 'void' between the parentheses. If you need nothing
there, there should be nothing.
>
string msg;
makeString(msg);
cout << "back in main, result = " << msg << endl;
return EXIT_SUCCESS;
}

void makeString(string& message){
char theMessage[25] = "Here is a char array";
message = theMessage;
cout << "insdie the makeString func,theMesage = '" << message <<
endl;
}

=====
=====

I would like to write functions that return strings that i can simply
assign to a string (or char*) from my calling function. The above
code achieves the result i want, but it looks a bit strange to me (I
have a java background). I would prefer the makeString function to
return the string, instead of adjusting a reference to a string that
is passed to it. I would rather it not take a variable at all.

The problem i have found is that making the string in the makeString()
function, then returning it does not work because the stackframe for
that function is destroyed when the function ends, so referencing a
tring variable in there makes no sense. I could make a string on the
heap and return a pointer to it, but then do i have manage freeing up
space for that string when i'm done using it in the calling mfunction?
this seems like a lot of extra work.
So, what's stopping you from defining your 'makeString' function like this:

std::string makeString() {
return "Here is a char array";
}

and using it accordingly?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 27 '08 #2
On May 20, 10:05 am, darren <minof...@gmail.comwrote:
The problem i have found is that making the string in the makeString()
function, then returning it does not work because the stackframe for
that function is destroyed when the function ends, so referencing a
tring variable in there makes no sense.
If you return an object that is constructed in a function it is copied
out of the function using the copy constructor so everything should
work as expected.
std::string data = getString();

std::string getString()
{
std::string result("Plop");

// The result object is copied out of the function.
return result;
}

If the result had been returned by reference then you would encounter
problems.
Jun 27 '08 #3
On May 20, 12:37 pm, Martin York <Martin.YorkAma...@gmail.comwrote:
On May 20, 10:05 am, darren <minof...@gmail.comwrote:
The problem i have found is that making the string in the makeString()
function, then returning it does not work because the stackframe for
that function is destroyed when the function ends, so referencing a
tring variable in there makes no sense.

If you return an object that is constructed in a function it is copied
out of the function using the copy constructor so everything should
work as expected.

std::string data = getString();

std::string getString()
{
std::string result("Plop");

// The result object is copied out of the function.
return result;

}

If the result had been returned by reference then you would encounter
problems.
cool, thanks for the helpful info Martin. I didn't know that
returning an object makes a copy of the object to pass back. What
would happen if you returned a reference to an object? If it
referenced something local, would the reference but null since that
stackframe is destroyed?

Also, say i had a statement like this:
char* myCString = "a string"
string myCppString = "another string"

I'm assuming that these string literals are stored on the heap? If so,
do i need to explicitly manage that memory? I thought I read that C++
handles those types of object automatically, but i"m not sure.

Victor: as for why its main(void), i copied some code created by the
Eclipse CDT C++ tool.
Jun 27 '08 #4

"darren" <mi******@gmail.comwrote in message
news:2d**********************************@s21g2000 prm.googlegroups.com...

<...>
I didn't know that
returning an object makes a copy of the object to pass back. What
would happen if you returned a reference to an object? If it
referenced something local, would the reference but null since that
stackframe is destroyed?
The best option to answer all these questions is to read the clc++ faq.

http://www.parashift.com/c++-faq-lite/index.html

regards
Andy Little
Jun 27 '08 #5
darren wrote:
On May 20, 12:37 pm, Martin York <Martin.YorkAma...@gmail.comwrote:
[...]
>If the result had been returned by reference then you would encounter
problems.

cool, thanks for the helpful info Martin. I didn't know that
returning an object makes a copy of the object to pass back. What
would happen if you returned a reference to an object? If it
referenced something local, would the reference but null since that
stackframe is destroyed?
int& reftoInt()
{
int i = 5;
return i; // don't do this!
}

i is an automatic variable that gets invalid when leaving the function,
so you return a reference to a lost object. Bad idea!

int& reftoStaticInt()
{
static int i = 5;
return i; // ok
}

A static variable has 'infinite' lifetime, you can pass a pointer or
reference to it around and can access it until the program ends.

int copyOfInt()
{
int i = 5;
return i; // ok, too
}

Since the return type is not a reference but normal object, the value
(5) will be copied before the local variable will be destroyed.
Also, say i had a statement like this:
char* myCString = "a string"
string myCppString = "another string"
A _string literal_ like "yet another string literal" has 'infinite'
lifetime (= lives until the program ends) just like a static variable.

const char* string1 = "a string";
This is a pointer to a string literal. Its valid until the program ends.

char string2[] = "a string";
This is a character array, initialized from a string literal (the
contents will be copied to the array). Defined in a function, it has
automatic lifetime (until end of function) and returning a pointer to
this array is a bad idea, since the pointer will point to invalid memory.

std::string string3 = "a string";
This is an object of class std::string. Just like string2, it is
initialized from a string literal. When defined locally in a function,
it will be destroyed on its end just like the char array, so returning a
pointer or reference to it is a bad idea, too. But you can return a full
object, so the string will be copied.
I'm assuming that these string literals are stored on the heap? If so,
do i need to explicitly manage that memory? I thought I read that C++
handles those types of object automatically, but i"m not sure.

Victor: as for why its main(void), i copied some code created by the
Eclipse CDT C++ tool.
int main(void) is idiomatic in C but discuraged (because unnecessary) in
C++.

--
Thomas
Jun 27 '08 #6
On May 20, 4:01 pm, "Thomas J. Gritzan" <phygon_antis...@gmx.de>
wrote:
darren wrote:
On May 20, 12:37 pm, Martin York <Martin.YorkAma...@gmail.comwrote:
[...]
If the result had been returned by reference then you would encounter
problems.
cool, thanks for the helpful info Martin. I didn't know that
returning an object makes a copy of the object to pass back. What
would happen if you returned a reference to an object? If it
referenced something local, would the reference but null since that
stackframe is destroyed?

int& reftoInt()
{
int i = 5;
return i; // don't do this!

}

i is an automatic variable that gets invalid when leaving the function,
so you return a reference to a lost object. Bad idea!

int& reftoStaticInt()
{
static int i = 5;
return i; // ok

}

A static variable has 'infinite' lifetime, you can pass a pointer or
reference to it around and can access it until the program ends.

int copyOfInt()
{
int i = 5;
return i; // ok, too

}

Since the return type is not a reference but normal object, the value
(5) will be copied before the local variable will be destroyed.
Also, say i had a statement like this:
char* myCString = "a string"
string myCppString = "another string"

A _string literal_ like "yet another string literal" has 'infinite'
lifetime (= lives until the program ends) just like a static variable.

const char* string1 = "a string";
This is a pointer to a string literal. Its valid until the program ends.

char string2[] = "a string";
This is a character array, initialized from a string literal (the
contents will be copied to the array). Defined in a function, it has
automatic lifetime (until end of function) and returning a pointer to
this array is a bad idea, since the pointer will point to invalid memory.

std::string string3 = "a string";
This is an object of class std::string. Just like string2, it is
initialized from a string literal. When defined locally in a function,
it will be destroyed on its end just like the char array, so returning a
pointer or reference to it is a bad idea, too. But you can return a full
object, so the string will be copied.
I'm assuming that these string literals are stored on the heap? If so,
do i need to explicitly manage that memory? I thought I read that C++
handles those types of object automatically, but i"m not sure.
Victor: as for why its main(void), i copied some code created by the
Eclipse CDT C++ tool.

int main(void) is idiomatic in C but discuraged (because unnecessary) in
C++.

--
Thomas
thomas, that saved me a lot of reading and searching for answers.
Thanks a lot for your time and help.
Jun 27 '08 #7
Thomas J. Gritzan wrote:
A _string literal_ like "yet another string literal" has 'infinite'
lifetime (= lives until the program ends) just like a static variable.
So to make things clear, this is ok?

const char* aString() { return "A string"; }
Jun 27 '08 #8
Juha Nieminen schrieb:
Thomas J. Gritzan wrote:
>A _string literal_ like "yet another string literal" has 'infinite'
lifetime (= lives until the program ends) just like a static variable.

So to make things clear, this is ok?

const char* aString() { return "A string"; }
Yes.

--
Thomas
Jun 27 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

41
by: Psykarrd | last post by:
I am trying to declare a string variable as an array of char's. the code looks like this. char name; then when i try to use the variable it dosn't work, however i am not sure you can use it...
4
by: agent349 | last post by:
First off, I know arrays can't be compared directly (ie: if (arrary1 == array2)). However, I've been trying to compare two arrays using pointers with no success. Basically, I want to take three...
4
by: Anthony | last post by:
Hello, I am writing a function that populates an array of pointers to strings. Both the number of strings in the array, and the lengths of the strings, are dynamic; in particular, the number of...
27
by: Ben Jacobs-Swearingen | last post by:
Hello, I just started learning C a couple weeks ago from Kernighan and Ritchie (first edition -- I can't afford the newer second edition), and have really enjoyed it so far. But I am having...
10
by: Ian Todd | last post by:
Hi, I am trying to read in a list of data from a file. Each line has a string in its first column. This is what i want to read. I could start by saying char to read in 1000 lines to the array( i...
3
by: Chris Mantoulidis | last post by:
I never liked pointers really much, so I decided to stay away from them for a while. I know they're useful, so now I decided to actually learn how the work, use them, etc. Here's my question......
5
by: shyam | last post by:
Hi All I have to write a function which basically takes in a string and returns an unknown number( at compile time) of strings i hav the following syntax in mind char *tokenize(char *) ...
23
by: TefJlives | last post by:
Hi all, I'm learning a bit about C, and I have a few questions. I'm not trying to insult C or anything with these questions, they're just honestly things I don't get. It seems like pointers...
19
by: bowlderyu | last post by:
Hello, all. If a struct contains a character strings, there are two methods to define the struct, one by character array, another by character pointer. E.g, //Program for struct includeing...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.