473,695 Members | 2,688 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(stri ng& 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 2215
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(stri ng& 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.comwr ote:
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******** *************** ***********@s21 g2000prm.google groups.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.comwr ote:
[...]
>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.comwr ote:
[...]
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
3948
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 the way i am trying to. Could some one please tell me what i am doing wrong, or another way of doing the same thing. i am trying to use the variable like this.
4
10532
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 sets of character strings from the user. Then I want to run through each element and compare the two strings. If they match I print they match... I'm having a bit of trouble with the actual loop through each array using the pointers and comparing...
4
4983
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 strings won't be known until just before the function returns. The problem is that in the calling function, I need to know both the address of the array, and the number of strings. My first thought was to pass a pointer to the array into the...
27
3372
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 trouble making the code at the end of Chapter 5 -- the sort function that uses function pointers -- to work on my machine (233 Mhz iMac, 160 MB RAM, OS 9.2 ; MPW environment). When I try to compile sort.c with the Symantec C compiler it gives me all...
10
9027
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 think!!). But I want to use malloc. Each string is at most 50 characters long, and there may be zero to thousands of lines. How do I actually start the array? I have seen char **array etc. At first I tried char *array but I think that gives 50...
3
1774
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... char *a = "some text"; char *b = "some other text"; Why will this work? Needn't I initialize the pointers first? (malloc
5
5478
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 *) is it ok?
23
4330
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 to chars are just how you deal with strings, and pointers to pointers to char just give you arrays of strings. What is the advantage of this vs. languages with a string type?
19
2042
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 character strings, test1.c #include <stdio.h> #define LEN 20 struct info {
0
8586
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9137
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8864
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7683
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5842
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4351
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3025
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2289
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1986
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.