quote:Original post by Viquel
In fact you don't wast memory.
If you call 10 times the function testMethod("HELLO"), it will create the HELLO string 10 time but once at a time, during the function call. The string will be automaticly released when the function will return.
Sorry Viquel but you're talking nonsense. Please remove your post to avoid misleading others.
Anyway, just to add some stuff that hasn't been mentioned previously:
#include <iostream>void testMethod( char *word){ std::cout<< word << "\n"; word[1] = 'u';// modify string that has been passed std::cout<< word << "\n";}
int main(){ char hello[] = "Hello";//creates an array of size 6 with values Hello\0 // where \0 is a single terminating character testMethod(hello);// passes a pointer to the array, hello, which is our own copy of "Hello" char* hell = "Hell";// creates a pointer to the constant string Hell\0 // which is stored somewhere in your executable // It is a constant and you're not allowed to change it// testMethod(hell);//crash! (uncomment this to see a crash) const char* nice = "Safe!";// testMethod(nice);// this line won't compile because testMethod takes a non-const // pointer to a char. The compiler can't be sure it won't be modified // so won't let you pass it. // This is safe. If you make testMethod only take a const char* you // can pass 'nice' but can't modify it in the function. return 0;}
The moral of the story is, if you're taking a pointer to a string literal then make it a const char*. Otherwise you could run into trouble somewher down the line.
Better yet, use std::string.
[edited by - petewood on May 1, 2003 6:27:15 PM]