473,839 Members | 1,674 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
36 2294

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**********@g mail.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********@sbc global.netwrote in message
news:a3******** ***********@new ssvr29.news.pro digy.net...
>
"Geo" <gg@remm.orgwro te in message
news:11******** **************@ l12g2000cwl.goo glegroups.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(&point er);
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,"Hel lo World");
std::cout << str << std::endl;
}

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

void strStuff(std::s tring &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(&point er);
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,"Hel lo 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::s tring &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(&point er);
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(&point er);
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
4522
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. So does Gnome::Vfs::FileInfo::get_name(). Isn't that unnecessary overhead? I could as well return by reference to const-string and avoid
4
4989
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...
12
2763
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 trying to get this to work, but been unable to solve my mistake. What the function should return is a file name used for creating logs files. It will look something like JN122345.log
7
2324
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
430
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 return the array? 2. How should the function be declared? 3. How is the return value captured by the calling program?
4
1664
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 ("".ToCharArray());
1
2087
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) { CDFDBSoapService.DBWebService dbws = new CDFDBSoapService.DBWebService(); Do the connection stuff here... return dbws.queryDatabase(sql); }
5
5487
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?
3
11782
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 parameter is used to find all associated open file
9
7919
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 List<as a property. Consider the example below, the class "ListTest" contains a private "List<>" called "strings" - it also provides a public method to add to that list,
0
9856
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10910
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...
0
10589
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10654
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
7021
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
5867
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4493
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
4066
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3136
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.