473,396 Members | 1,996 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,396 software developers and data experts.

returning strings

how do we return strings or arrays from a function? i tried..

char[] some_func() //where i thought char[] would tell the compiler
that the return is a string
{

char str[100];
//something;
return str;
}
thanks in advance!

Dec 7 '06 #1
36 2228
Geo
MC felon wrote:
how do we return strings or arrays from a function? i tried..

char[] some_func() //where i thought char[] would tell the compiler
that the return is a string
{

char str[100];
//something;
return str;
}
thanks in advance!
You're writting C++ not C, do it like this

std::string some_func()
{
std::string str;
// something;
return str;
}

Dec 7 '06 #2
i work on TC++ (some old version). Please suggest something that works
in the same.

Dec 7 '06 #3
MC felon wrote:
how do we return strings or arrays from a function? i tried..

char[] some_func() //where i thought char[] would tell the compiler
that the return is a string
{

char str[100];
//something;
return str;
}
That won't work too well since by the time the function returns the
value being returned is dead.

Did you read the FAQ?
Dec 7 '06 #4

how does the function 'gets()' return the string?

Dec 7 '06 #5
MC felon wrote:
>
how does the function 'gets()' return the string?
It doesn't. You give it the memory, and the function fills it.

Dec 7 '06 #6

Rolf Magnus wrote:
MC felon wrote:

how does the function 'gets()' return the string?

It doesn't. You give it the memory, and the function fills it.
You give it the memory, and the function fills it, and the function
merrily continues filling memory past the end of the chunk you gave it
until the input is used up, and, unless your program has ABSOLUTE
control over the length of the input[*], there is absolutely nothing
you can do to prevent this risk.

To the OP: Don't use gets. If you are going to use C funcitons for
string input, use fgets.
[*] prompting the user to only type a certain number of characters is
by no means absolute control.

Gavin Deane

Dec 7 '06 #7

MC felon wrote:
i work on TC++ (some old version). Please suggest something that works
in the same.
Please quote enough of the message you are replying to to provide
context. On its own, your message is meaningless. To do that from
Google Groups, don't use the broken Reply link at the bottom of the
message. Instead, click the Show Options link at the top and use the
Reply link revealed there. Thanks.

To answer your question, did you #include<string>, the standard header
that defines the C++ string class (and puts it in namespace std)?

As to your compiler, if you can't get this

#include <string>
std::string some_func()
{
std::string str;
// something;
return str;
}

to compile, you haven't got a hope of learning or writing C++ with that
compiler. Fortunately, there are sevral up-to-date and free C++
compilers available for you to upgrade to. If you're on Windows,
Microsoft's VC++8 compiler is free for example, and there are other
options. If you're on a different platform there will, I am sure, be
other options too.

Gavin Deane

Dec 7 '06 #8
Geo

MC felon wrote:
i work on TC++ (some old version). Please suggest something that works
in the same.
Since I don't know what TC++ is, I don't know what works,. but if it
doesn't support the STL it isn't really C++ as I know it.

If you don't know how to work with C style strings, I suggest you read
a book, it's far to complicated to describe here.

Dec 7 '06 #9

ok. thanks for the tip.
here's what i want the function to do.

allow the user to input a string. stop receiving input when user
presses tab.

its like gets, only that the input gets stopped when '\t' is pressed
and not '\r'.

how do i do this?

Dec 7 '06 #10
Geo

MC felon wrote:
ok. thanks for the tip.
here's what i want the function to do.

allow the user to input a string. stop receiving input when user
presses tab.

its like gets, only that the input gets stopped when '\t' is pressed
and not '\r'.

how do i do this?
You can't, not in staandard C++ anyway.

Dec 7 '06 #11
Geo wrote:
MC felon wrote:
>ok. thanks for the tip.
here's what i want the function to do.

allow the user to input a string. stop receiving input when user
presses tab.

its like gets, only that the input gets stopped when '\t' is pressed
and not '\r'.

how do i do this?

You can't, not in staandard C++ anyway.
Strictly speaking, you can using "readsome()", but I would strongly
suggest not doing it that way.
Dec 7 '06 #12

MC felon wrote:
ok. thanks for the tip.
here's what i want the function to do.

allow the user to input a string. stop receiving input when user
presses tab.

its like gets, only that the input gets stopped when '\t' is pressed
and not '\r'.

how do i do this?
std::getline allows you to choose any delimiter character you want. The
default is newline but you can change that. This shows how it works.

#include <string>
#include <sstream>
#include <iostream>
using namespace std;

int main()
{
string input("abc\tdef\nghi");
istringstream iss(input);
string read_to_newline;
getline(iss, read_to_newline);
iss.str(input);
string read_to_tab;
getline(iss, read_to_tab, '\t');

cout << read_to_newline << "\n";
cout << read_to_tab << "\n";
}

In your case, the input is not a string within the program, it is the
user typing at the console. So replace the istringstream in my example
with cin.

Gavin Deane

Dec 7 '06 #13

MC felon wrote:
i work on TC++ (some old version). Please suggest something that works
in the same.
Please quote the message you are responding to.

This newsgroup is about C++, not some particular out-of-date compiler.
Any compiler that hopes to use C++ should at very least support the
<stringclass.
Thats a bare minimum.
And since there are reasonably-compliant, free compilers out there,
i'ld suggest using one of them (ie: VC Express or g++). Many of these
come with capable IDEs as well.

You could write something like the following although that only works
because the const char* is static.

#include <iostream>
#include <ostream>

const char* const getstr()
{
static const char* const p_str = "a static string";
return p_str;
}

int main()
{
std::cout << getstr() << std::endl;
}

Passing arrays around is tricky and ugly. What you cannot do is
generate a temporary array and return a pointer to it. Thats begging
for disaster since functions have no state. So you'ld have to make the
array static (ewww). Arrays of chars are not equipped with a
terminator, something that a char* requires. So if you need an array of
10 chars:

#include <iostream>
#include <ostream>

const char* const str()
{
const size_t Size(10);
static char array[Size + 1]; // static !

char c = 'a';
for( size_t i = 0; i < Size; ++i )
{
array[i] = c++;
}
array[Size + 1] = '\0'; // terminator
return array;
}

int main()
{
std::cout << str() << std::endl;
}

/*
abcdefghij
*/

Dec 7 '06 #14

"Geo" <gg@remm.orgwrote in message
news:11**********************@l12g2000cwl.googlegr oups.com...
>
MC felon wrote:
>i work on TC++ (some old version). Please suggest something that works
in the same.

Since I don't know what TC++ is, I don't know what works,. but if it
doesn't support the STL it isn't really C++ as I know it.


TC++ is Borlands Turbo C++, I am assuming, and yes it does support the STL
Strings library.
>
If you don't know how to work with C style strings, I suggest you read
a book, it's far to complicated to describe here.

However if You need to return a string value without using the string
library, you either need to return a pointer to a string that was allocated
on the heap with malloc; ie:

char * somefunc()
{
char * tmp = malloc(100);
tmp = "hello world\0";
return tmp;
};

or you need to pass the function a string by reference and return the
result in that.
void somefunc(char *tmp)
{
tmp = "Hello World!\0";
}

void main()
{
char[100] Str;
somefunc(&Str);
}
Dec 7 '06 #15
Gavin Deane wrote:
>
MC felon wrote:
>ok. thanks for the tip.
here's what i want the function to do.

allow the user to input a string. stop receiving input when user
presses tab.

its like gets, only that the input gets stopped when '\t' is pressed
and not '\r'.

how do i do this?

std::getline allows you to choose any delimiter character you want. The
default is newline but you can change that. This shows how it works.

#include <string>
#include <sstream>
#include <iostream>
using namespace std;

int main()
{
string input("abc\tdef\nghi");
istringstream iss(input);
string read_to_newline;
getline(iss, read_to_newline);
iss.str(input);
string read_to_tab;
getline(iss, read_to_tab, '\t');

cout << read_to_newline << "\n";
cout << read_to_tab << "\n";
}

In your case, the input is not a string within the program, it is the
user typing at the console. So replace the istringstream in my example
with cin.
However, the cin stream might be (and usually is) line buffered. In that
case, the getline call gives you everything up to the next tab character,
but the program will not receive the data until the user presses return or
the buffer is full.
In standard C++, there is no way to avoid that behavior.
Dec 7 '06 #16
MC felon wrote:
i work on TC++ (some old version). Please suggest something that works
in the same.
I'd rather suggest to upgrade to a newer compiler that a standard library
implementation exists for. Without std::string (or another string classs)
you have to deal with all the complicated and obscure details of pointers,
arrays and dynamic memory handling just for doing some simple string
operations.
Dec 7 '06 #17
David Pratt wrote:
However if You need to return a string value without using the string
library, you either need to return a pointer to a string that was
allocated on the heap with malloc; ie:

char * somefunc()
{
char * tmp = malloc(100);
tmp = "hello world\0";
return tmp;
};
Here you see what happens if you try to do C style string handling without
knowing every detail about memory handling, arrays and pointers. The above
function leaks memory. First, 100 bytes are allocated, and that memory
block's address is stored in tmp. In the next line, the pointer tmp gets
overwritten by the address of the string literal "hello world\0" (btw:
String literals already have a terminating \0 character. No need to
explicitly add a second one). Since there is no pointer anymore to the
dynamically allocated block of memory, that memory is lost forever. Now the
address of the string literal is returned. That part is ok, because string
literals have static storage duration. However, you returned a pointer to
non-const, and the literal is actually constant. An attempt to write to it
results in undefined behavior. Attempting to delete it, too.
What you should actually have done is use the strcpy function to copy the
string literal's content over to the dynamic memory (and document in red
uppercase letters that the user of the function is responsible for deleting
the memory).
or you need to pass the function a string by reference and return the
result in that.
void somefunc(char *tmp)
{
tmp = "Hello World!\0";
}
Well, this function is actually a no-op. tmp is a local pointer. You
overwrite this pointer, then the function returns. The local pointer is
destroyed, and nothing outside the function has changed. Again, you should
have used strcpy.
void main()
main() must return int.
{
char[100] Str;
That would have to be:

char Str[100];
somefunc(&Str);
And that:

somefunc(Str);
}
I'm sorry, but you must either have been drunk when you wrote that or you
shouldn't give advice about pointers and arrays in C++.

Dec 7 '06 #18
Geo

David Pratt wrote:

If you don't know how to work with C style strings, I suggest you read
a book, it's far to complicated to describe here.
However if You need to return a string value without using the string
library, you either need to return a pointer to a string that was allocated
on the heap with malloc; ie:

char * somefunc()
{
char * tmp = malloc(100);
tmp = "hello world\0";
return tmp;
};
Oh no,no,no,no,no, how badly wrong can you go !!!!

I suggest you also need to read a book on memory handling.

Please refrain from giving any more 'advice' on the subject until you
do.

Dec 7 '06 #19

Rolf Magnus wrote:
Gavin Deane wrote:

MC felon wrote:
ok. thanks for the tip.
here's what i want the function to do.

allow the user to input a string. stop receiving input when user
presses tab.

its like gets, only that the input gets stopped when '\t' is pressed
and not '\r'.

how do i do this?
std::getline allows you to choose any delimiter character you want. The
default is newline but you can change that. This shows how it works.
<snip program that works with istringstream>
In your case, the input is not a string within the program, it is the
user typing at the console. So replace the istringstream in my example
with cin.

However, the cin stream might be (and usually is) line buffered. In that
case, the getline call gives you everything up to the next tab character,
but the program will not receive the data until the user presses return or
the buffer is full.
In standard C++, there is no way to avoid that behavior.
Somehow I knew that testing the code with an istringstream (which was
easier because I could do it all programatically) was a shortcut that
wasn't quite valid. I should have thought it through properly (or just
tested it myself!). Thanks for pointing out the mistake.

Gavin Deane

Dec 7 '06 #20
Geo

Gianni Mariani wrote:
>
Strictly speaking, you can using "readsome()", but I would strongly
suggest not doing it that way.

Hi Gianni,

Does that work even if the stream is buffered ? I've never noticed that
function before, but then I've never need that kind of functionality.

Dec 7 '06 #21
Geo wrote:
Gianni Mariani wrote:
>Strictly speaking, you can using "readsome()", but I would strongly
suggest not doing it that way.


Hi Gianni,

Does that work even if the stream is buffered ? I've never noticed that
function before, but then I've never need that kind of functionality.
It's a way of reading out of your buffer (istream) and the input file
without waiting. I don't know how well it is supported but gcc
implements it correctly.

Dec 7 '06 #22
In response to Rolf and Geo who both seem to think I did not know what the
heck I was talking about, Yes I know that the sample program leaks memory;
I f it was a real world situation, I would most definately have released the
memory when I was through; however I was trying to succinctly demonstrate
answers to the OPs question, which effectively was, "How can you return an
array of characters (more commonly know as a string) to a calling function?"
My Sample does that on both counts. If you don't believe me, try the samples
with one slight mod: I did forget to typecast the malloc function return to
a char * in the first. :s
Dec 8 '06 #23

David Pratt wrote:
In response to Rolf and Geo who both seem to think I did not know what the
heck I was talking about, Yes I know that the sample program leaks memory;
I f it was a real world situation, I would most definately have released the
memory when I was through;
Really? Where?
Evan

Dec 8 '06 #24
I V
On Fri, 08 Dec 2006 02:52:22 +0000, David Pratt wrote:
In response to Rolf and Geo who both seem to think I did not know what the
heck I was talking about, Yes I know that the sample program leaks memory;
I f it was a real world situation, I would most definately have released the
memory when I was through; however I was trying to succinctly demonstrate
--- your code ---
char * somefunc()
{
char * tmp = malloc(100);
tmp = "hello world\0";
return tmp;
};
--- end ---

How would you free the allocated memory in this case? I don't think you
can.
Dec 8 '06 #25

David Pratt wrote:
In response to Rolf and Geo who both seem to think I did not know what the
heck I was talking about, Yes I know that the sample program leaks memory;
I f it was a real world situation, I would most definately have released the
memory when I was through; however I was trying to succinctly demonstrate
answers to the OPs question, which effectively was, "How can you return an
array of characters (more commonly know as a string) to a calling function?"
My Sample does that on both counts. If you don't believe me, try the samples
with one slight mod: I did forget to typecast the malloc function return to
a char * in the first. :s
Well, when they're right...and after reviewing your answer I have to
say they are right. You either don't know C++ or you just plain where
not thinking clearly when you wrote your reply. Rolf actually gave a
very thurough explaination of why you are wrong and you should go back
and read it if you still don't know you are. As to your challenge I
decided to take you up on it with the one that would most obviously
show your error by simply not returning the value you are attempting to
return:

#include <iostream>
using namespace std;

void str_stuff(char * str)
{
str = "Hello world";
}

int main(void)
{
char str[20] = "Not Hello World";

str_stuff(str);

cout << str << endl;

}
nroberts@localhost ~/projects/garbage $ g++ bad_char.cpp
nroberts@localhost ~/projects/garbage $ ./a.out
Not Hello World
Now, as to the casting of malloc...this is C++, you shouldn't even be
using it.

I'm not trying to gang up on you but your answer really was quite
mistaken. Go back and re-read Rolf's post to better understand why.

Dec 8 '06 #26

"Noah Roberts" <ro**********@gmail.comwrote in message
news:11**********************@73g2000cwn.googlegro ups.com...
>
David Pratt wrote:
>In response to Rolf and Geo who both seem to think I did not know what
the
heck I was talking about, Yes I know that the sample program leaks
memory;
I f it was a real world situation, I would most definately have released
the
memory when I was through; however I was trying to succinctly demonstrate
answers to the OPs question, which effectively was, "How can you return
an
array of characters (more commonly know as a string) to a calling
function?"
My Sample does that on both counts. If you don't believe me, try the
samples
with one slight mod: I did forget to typecast the malloc function return
to
a char * in the first. :s

Well, when they're right...and after reviewing your answer I have to
say they are right. You either don't know C++ or you just plain where
not thinking clearly when you wrote your reply. Rolf actually gave a
very thurough explaination of why you are wrong and you should go back
and read it if you still don't know you are. As to your challenge I
decided to take you up on it with the one that would most obviously
show your error by simply not returning the value you are attempting to
return:

#include <iostream>
using namespace std;

void str_stuff(char * str)
{
str = "Hello world";
}

int main(void)
{
char str[20] = "Not Hello World";

str_stuff(str);
Ah, but you're passing the argument by value, and of course that won't
change anything. Pass the argument by reference thus

str_stuff(&str);

as in my example and see what happens.
>
cout << str << endl;

}
nroberts@localhost ~/projects/garbage $ g++ bad_char.cpp
nroberts@localhost ~/projects/garbage $ ./a.out
Not Hello World
Now, as to the casting of malloc...this is C++, you shouldn't even be
using it.
Why not? I would be willing to take bets that at some level, the STL uses
the same system to allocate memory for its objects. I was meerly trying to
demonstrate in the simplest manner possible how to return strings to a
calling function. Templates are an advanced topic, and from the tone of the
OP, I was under the impression that he was a novice, and I geared my
response towards that level. I did not mean to whip up a firestorm of
hysterical responses; just trying to pass along some pointers that i've
picked up along the way to help build a knowledge of why things work the way
they do.
>
I'm not trying to gang up on you but your answer really was quite
mistaken. Go back and re-read Rolf's post to better understand why.
I would , but I get so turned off by his hysterical ranting and insults that
I just skip on past it. Always been like that since I was a kid; my mom
would start in on me and I would just tune her out.
Dec 8 '06 #27
IR
David Pratt wrote:
"Noah Roberts" <ro**********@gmail.comwrote in message
news:11**********************@73g2000cwn.googlegro ups.com...
>>
David Pratt wrote:
>>In response to Rolf and Geo who both seem to think I did not
know what the
heck I was talking about, Yes I know that the sample program
leaks memory;
I f it was a real world situation, I would most definately have
released the
memory when I was through;
For the record, here is the code concerned:

char * somefunc()
{
char * tmp = malloc(100);
tmp = "hello world\0";
return tmp;
};

When exactly would you release the memory?
[...]
>#include <iostream>
using namespace std;

void str_stuff(char * str)
{
str = "Hello world";
}

int main(void)
{
char str[20] = "Not Hello World";

str_stuff(str);

Ah, but you're passing the argument by value, and of course that
won't change anything. Pass the argument by reference thus

str_stuff(&str);

as in my example and see what happens.
Did you even try to compile your code?
Here is what happens (once corrected the syntax errors):

'somefunc' : cannot convert parameter 1 from 'char (*__w64)[100]' to
'char *'. Types pointed to are unrelated; conversion requires
reinterpret_cast, C-style cast or function-style cast
[...]
from the tone of the OP, I was under the
impression that he was a novice, and I geared my response towards
that level. I did not mean to whip up a firestorm of hysterical
responses; just trying to pass along some pointers that i've
picked up along the way to help build a knowledge of why things
work the way they do.
Not to be rude, but maybe you should then learn *how* things actually
work, before trying to understand *why* they work like they do.

>I'm not trying to gang up on you but your answer really was quite
mistaken. Go back and re-read Rolf's post to better understand
why.
I would , but I get so turned off by his hysterical ranting and
insults that I just skip on past it. Always been like that since
I was a kid; my mom would start in on me and I would just tune
her out.
IMHO Rolf is not the one being hysterical here...

Cheers,
--
IR
Dec 8 '06 #28
Geo

David Pratt wrote:
#include <iostream>
using namespace std;

void str_stuff(char * str)
{
str = "Hello world";
}

int main(void)
{
char str[20] = "Not Hello World";

str_stuff(str);

Ah, but you're passing the argument by value, and of course that won't
change anything. Pass the argument by reference thus

str_stuff(&str);
Oh dear, you're just digging a deeper hole for yourself, that's not a
pass by value, and your example is NOT a reference !
>
as in my example and see what happens.

cout << str << endl;

}
nroberts@localhost ~/projects/garbage $ g++ bad_char.cpp
nroberts@localhost ~/projects/garbage $ ./a.out
Not Hello World
Now, as to the casting of malloc...this is C++, you shouldn't even be
using it.

Why not?
Because it's not typesafe, it's not the C++ way and it's also one
instance where C++ is not the same as C, malloc in C shouldn't be
typecast, in C++ it should.
>I would be willing to take bets that at some level, the STL uses
the same system to allocate memory for its objects.
So what ?
I was meerly trying to
demonstrate in the simplest manner possible how to return strings to a
calling function. Templates are an advanced topic, and from the tone of the
OP, I was under the impression that he was a novice, and I geared my
response towards that level. I did not mean to whip up a firestorm of
hysterical responses; just trying to pass along some pointers that i've
picked up along the way to help build a knowledge of why things work the way
they do.

But your example was completely broken, it was of no use to the OP
whatsoever, except to show him how NOT to do it I suppose, or to show
just how easy it is to get into a mess with C-style strings, if you
don#t know what you're doing.


I'm not trying to gang up on you but your answer really was quite
mistaken. Go back and re-read Rolf's post to better understand why.
I would , but I get so turned off by his hysterical ranting and insults that
I just skip on past it. Always been like that since I was a kid; my mom
would start in on me and I would just tune her out.

Maybe that's why you think you're right, when in fact you're completly
wrong, clue, LISTEN !!!!

Dec 8 '06 #29
Now, as to the casting of malloc...this is C++, you shouldn't even be
using it.

Why not? I would be willing to take bets that at some level, the STL uses
the same system to allocate memory for its objects.
Eventually, probably through new, but that's implementation defined.

In the case in which you're creating an object rather than a primitive
type, malloc won't call the constructor. This means that if you use
malloc, you're either going to miss out on that behavior or have a mix
of using new and malloc everywhere, which means tracking which objects
were allocated with each technique so that you can free them properly.

(On the DeathStation 9000
(http://en.wikipedia.org/wiki/DeathStation_9000), calling free with a
pointer pointing to a region of memory allocated with new, or calling
delete with a pointer pointing to mallocd space, will corrupt your
program in just the right way for it to do the worst thing possible. In
practical terms... I have a hard time envisioning an implementer *not*
writing new in terms of malloc and delete in terms of free. Though
maybe someone here will correct me on this point. ;-))
I was meerly trying to
demonstrate in the simplest manner possible how to return strings to a
calling function. Templates are an advanced topic, and from the tone of the
OP, I was under the impression that he was a novice, and I geared my
response towards that level.
What's all this about templates? We're saying use 'new'.
Evan

Dec 8 '06 #30

David Pratt wrote:
I was meerly trying to
demonstrate in the simplest manner possible how to return strings to a
calling function. Templates are an advanced topic, and from the tone of the
OP, I was under the impression that he was a novice, and I geared my
response towards that level.
The OP was trying to return a string from a function. The simplest
manner possible in C++ is to use std::string. In C++, manual memory
management and C-style strings are more advanced topics than
std::string. Templates have nothing to do with it. std::string happens
to be a typedef for a specialisation of a template class. There is
absolutely no need to know what that means or how to write one before
you start using std::string.

Gavin Deane

Dec 8 '06 #31

David Pratt wrote:
"Noah Roberts" <ro**********@gmail.comwrote in message
#include <iostream>
using namespace std;

void str_stuff(char * str)
{
str = "Hello world";
}
Ah, but you're passing the argument by value, and of course that won't
change anything. Pass the argument by reference thus

str_stuff(&str);

as in my example and see what happens.
It doesn't compile. The signature of your function expects a pointer,
not a reference to a pointer nor a pointer to a pointer and certainly
not a pointer to a char[20].

Now, as to the casting of malloc...this is C++, you shouldn't even be
using it.

Why not?
Because unless you need to be able to compile the code with a C
compiler you are a lot better off using the new operator.
>

I'm not trying to gang up on you but your answer really was quite
mistaken. Go back and re-read Rolf's post to better understand why.
I would , but I get so turned off by his hysterical ranting and insults that
I just skip on past it. Always been like that since I was a kid; my mom
would start in on me and I would just tune her out.
Hmmm....ok. Maybe your perception of what he said is just
off...something to consider. From what I can see he plainly stated
what the problem is in your code and you still don't seem to see it.
You really should read what he has written because you have something
to learn in this area.

Dec 8 '06 #32

"David Pratt" <Pr********@sbcglobal.netwrote in message
news:a3*******************@newssvr29.news.prodigy. net...
>
"Geo" <gg@remm.orgwrote in message
news:11**********************@l12g2000cwl.googlegr oups.com...
>>
>

However if You need to return a string value without using the string
library, you either need to return a pointer to a string that was
allocated on the heap with malloc; ie:

char * somefunc()
{
char * tmp = malloc(100);
It's better to use new[] in C++. (And if you use malloc, you ned to cast
the result to char*, right?)
tmp = "hello world\0";
Oops. This is not how to copy data to a char array. Use strcpy().
return tmp;
};
(Don't forget to document that the caller of this function now needs to free
the memory. And if you change it to use new[], then make sure to use
delete[] to free that memory.)

or you need to pass the function a string by reference and return the
result in that.
void somefunc(char *tmp)
{
tmp = "Hello World!\0";
}
That's not "by reference". You're passing a pointer, not a reference.

Again, assignment here does not do what you're thinking it does. Use
strcpy() (or strncpy()) to copy char data into a C-style string.

Another good practice, when filling arrays passed to you via a pointer, is
to also add a parameter telling the function how big the array is, so that
it can be sure it does not overrun the array given to it.

-Howard

Dec 8 '06 #33
LR
David Pratt wrote:
>>#include <iostream>
using namespace std;

void str_stuff(char * str)
{
str = "Hello world";
That does change str, but only the copy that is local to str_stuff.
>>}

int main(void)
{
char str[20] = "Not Hello World";

str_stuff(str);


Ah, but you're passing the argument by value, and of course that won't
change anything. Pass the argument by reference thus

str_stuff(&str);
That's not a reference. And I'm not sure it's at all legal. My
compiler gives an error and lint does the same. Although, I can get it
to compile with:
str_stuff(&str[0]);
Is that what you meant?
>
as in my example and see what happens.

> cout << str << endl;

}
Well, I tried it the way that I could get it to compile and the output
was "Not Hello World"

Try to imagine what the compiler does when it sees something like:

char str[20] = "A";

Most likely, the compiler will reserve 20 chars somewhere (in this case
probably on a stack since it's not static) and use the label str to
refer (str is not a C++ reference) to that space. "str" isn't pointer
and can't change the place it refers to. In that way, it is something
like a reference in that it can't be reseated, or, str is something more
like "char * const str" then "char * str". These descriptions are
informal.

If you want to do something like this with pointers then perhaps this
will work for you:

#include <iostream>
#include <string>
void strStuff(char **s)
{
*s = "Hello world";
}
int main()
{
char array[20] = "Not Hello World";
char *pointer = array;
std::cout << pointer << std::endl;
strStuff(&pointer);
std::cout << pointer << std::endl;
}

I believe that the "Hello World" will actually persist and so this is, I
think, safe. But I could be wrong about that. Even if I'm right, it's
probably not good code since it's possible in future that some language
rule change will make this illegal. As it is, the line in strStuff
yields an informative message in lint because it's not const safe.

Consider this snippet and the dangers of using strcpy:
int main()
{
char str[20] = "Not Hello World";
strcpy(str,"Hello World");
std::cout << str << std::endl;
}

Consider this code and the relative safety of using std::string
#include <iostream>
#include <string>

void strStuff(std::string &str)
{
str = "Hello world";
}

int main()
{
std::string str = "Not Hello World";
strStuff(str);
std::cout << str << std::endl;
}
Dec 8 '06 #34

LR wrote:
If you want to do something like this with pointers then perhaps this
will work for you:

#include <iostream>
#include <string>
void strStuff(char **s)
{
*s = "Hello world";
}
int main()
{
char array[20] = "Not Hello World";
char *pointer = array;
std::cout << pointer << std::endl;
strStuff(&pointer);
std::cout << pointer << std::endl;
}

I believe that the "Hello World" will actually persist and so this is, I
think, safe. But I could be wrong about that. Even if I'm right, it's
probably not good code since it's possible in future that some language
rule change will make this illegal. As it is, the line in strStuff
yields an informative message in lint because it's not const safe.
Lint is correct. The code has subtle problems and any attempt to
modify pointer's data after the call to strStuff will cause problems.
Consider this snippet and the dangers of using strcpy:
int main()
{
char str[20] = "Not Hello World";
strcpy(str,"Hello World");
std::cout << str << std::endl;
}
This is of course the right way to do it. As was explained by Rolf
many posts ago. The whole issue behind the bad code is that string
operations are not used but instead pointers are overwritten.
>
Consider this code and the relative safety of using std::string
#include <iostream>
#include <string>

void strStuff(std::string &str)
{
str = "Hello world";
}

int main()
{
std::string str = "Not Hello World";
strStuff(str);
std::cout << str << std::endl;
}
Yes, this is the best way to do it.

Dec 8 '06 #35

Noah Roberts wrote:
LR wrote:
If you want to do something like this with pointers then perhaps this
will work for you:

#include <iostream>
#include <string>
void strStuff(char **s)
{
*s = "Hello world";
}
int main()
{
char array[20] = "Not Hello World";
char *pointer = array;
std::cout << pointer << std::endl;
strStuff(&pointer);
std::cout << pointer << std::endl;
}

I believe that the "Hello World" will actually persist and so this is, I
think, safe. But I could be wrong about that. Even if I'm right, it's
probably not good code since it's possible in future that some language
rule change will make this illegal. As it is, the line in strStuff
yields an informative message in lint because it's not const safe.

Lint is correct. The code has subtle problems and any attempt to
modify pointer's data after the call to strStuff will cause problems.
Modification's out, but use of that pointer is kosher, right? (Maybe
not good idea, but at least correct.)

Evan

Dec 8 '06 #36

Evan wrote:
Noah Roberts wrote:
LR wrote:
If you want to do something like this with pointers then perhaps this
will work for you:
>
#include <iostream>
#include <string>
void strStuff(char **s)
{
*s = "Hello world";
}
int main()
{
char array[20] = "Not Hello World";
char *pointer = array;
std::cout << pointer << std::endl;
strStuff(&pointer);
std::cout << pointer << std::endl;
}
>
I believe that the "Hello World" will actually persist and so this is, I
think, safe. But I could be wrong about that. Even if I'm right, it's
probably not good code since it's possible in future that some language
rule change will make this illegal. As it is, the line in strStuff
yields an informative message in lint because it's not const safe.
Lint is correct. The code has subtle problems and any attempt to
modify pointer's data after the call to strStuff will cause problems.

Modification's out, but use of that pointer is kosher, right? (Maybe
not good idea, but at least correct.)
Use yes, but there is nothing to tell you that the data pointed to is
constant. Once you get very far removed from the point of change it
will be less and less obvious that you can't write to the pointer.
Someone is bound to.

Dec 8 '06 #37

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

Similar topics

13
by: Matthias Kaeppler | last post by:
Hi, I was wondering why library implementors often make getter functions return strings by value (copies). For example, in boost::filesystem the leaf() function returns an std::string by value....
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...
12
by: LongBow | last post by:
Hello all, From doing a google serach in the newsgroups I found out that a string can't be returned from a function, but using a char* I should be able to do it. I have spent most of the day...
7
by: wonderboy | last post by:
Hey guys, I have a simple question. Suppose we have the following functions:- //-----My code starts here char* f1(char* s) { char* temp="Hi"; return temp;
6
by: karthika.28 | last post by:
Hi, I am writing a function that needs to return an array of strings and I am having some trouble getting it right. Can you help me answer the following questions? 1. How does the function...
4
by: Jon Skeet | last post by:
I've just noticed something rather odd and disturbing. The following code displays "True": using System; class Test { public static void Main(string args) { string x = new string...
1
by: Randy | last post by:
Hello, I have a web service in which I'm doing a query to an Access database and returning the resulting XML data when I do the return from the service... public string AOS_Data(string sql) {...
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 *) ...
3
by: DG is a god.... | last post by:
Dear All , This is my first post - please go easy...! I have a DLL written in C++ that has the following function exported from it -: char** ListHandles(int *processID); The processID...
9
by: Paul | last post by:
Hi, I feel I'm going around circles on this one and would appreciate some other points of view. From a design / encapsulation point of view, what's the best practise for returning a private...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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,...

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.