Re: Copying char array ....
Wolfgang wrote:
The intention behind the program is to do a copy of one string
to other...
dest = source ;
works for me.
int mycpy(char &dest, char &src) //fn accept's the address..
char is NOT the type of a string, std::string is the type of a
string. So this should be:
int mycpy( std::string& dest, std::string const& source )
Except that there really isn't any reason to put it in a
function (and I don't see what the int return value is doing
here).
Also note the const on the source parameter. Presumably, since
it is the source, you're not modifying it.
{
dest=src; // assigning the source string address to
destination string
address...
Works fine with the correct declaration above.
return 1;
}
int main()
{
char deststr[100];
This is an array of char---in modern C++, we'd generally prefer:
std::vector< char > deststr( 100 ) ;
It is NOT a string. To declare a string:
std::string destString ;
char srcstr[] = "This is my test string";
This is also an array of char, initialized with a string
literal. For historical reasons, the type of string literals is
char const[], rather than std::string, but they convert
implicitly to std::string whenever needed.
Note too that you have declared an array which you will be
modifying.
int size=0;
if( (size=mycpy(deststr,srcstr)) > 0) //Trying to pass the address
of
'deststr' and 'srcstr'
This shouldn't compile, neither with your definition (which
expects char's) of mycpy, nor with mine (which expects strings).
printf("%s , size = %d\n",deststr,strlen(deststr));
return 0;
}
The above code performs well, if the mycpy fn definiton is like this..
int mycpy(char *dest, char *src)
{
int i=0;
while( (dest[i]=src[i])!='\0')
i++;
return i;
}
For historical reasons only. That's the way you would have
written it in pre-standard C. Even in standard C, there would
be a const or two, but you'd still be forced to hack it more or
less like this, because there is no string type. In C++,
however, why bother?
Can we assign address this way ?
In what way? I don't see a single assign of an address in your
code. But in C++, poihter variables are objects, and can be
assigned, just like anything else.
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]