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;
}