Question

sorry for another string copy question.. but I really can't find the reason why in my code, strTo can be printed, but strFinal can't in neither way.

cout << strTo << endl;

cout << strFinal << endl;
while (*strFinal != '\0') {
    cout << *strFinal++;
}

Appreciated if someone can point it out where I misunderstood about pointers and arrays! Thanks!

#include <iostream>

using namespace std;

char *str_copy (const char *strFrom, char *strTo) 
{
    while (*strFrom != '\0') {
        *strTo++ = *strFrom++;
    }
    *strTo = '\0';
    return strTo;
}

int main()
{
    char strFrom[]="abc123";
    char strTo[10];
    char *strFinal = str_copy(strFrom, strTo);

    cout << strTo << endl;

    cout << strFinal << endl;
    while (*strFinal != '\0') {
        cout << *strFinal++;
    }

    return 0;
}

Additional Question:

I don't know the reason when I put the code in main function like this:

char strFrom[]="abc123";
char strTo[10];
strTo = str_copy(strFrom, strTo);

Then complier said:

main.cpp:18: error: array type 'char [10]' is not assignable strTo = str_copy(strFrom, strTo); ~~~~~ ^

How should I correct in this way? Thanks!

Was it helpful?

Solution

The function returns a pointer to the terminating zero.

char *str_copy (const char *strFrom, char *strTo) 
{
    //...
    *strTo = '\0';
    return strTo;
}

Change it the following way

char *str_copy (const char *strFrom, char *strTo) 
{
    char *p = strTo;
    while ( *p++ = *strFrom++ );

    return strTo;
}

Also I would declare it the same way as standard C function strcpy is declared

char *str_copy( char *strTo, const char *strFrom );

As for your additional question then you may not assign a pointer or even other array to an array. So the compiler issues the error.

Arrays have no the assignment operator. You can only copy their elements. Otherwise use standard class std::array.

OTHER TIPS

After returning from str_copy you strTo does not point to the beginning of your copied string. In main strTo is ok, because it was passed by value (address of pointer after returning from str_copy is not changed even though you were using strTo++). But returned value of strFinal points to last character of copied string - '\0'.

For second part - char[10] has unchangeable addres, so you can't assign anything to variable of this type, like you tried in strTo = str_copy(...);.

Your second question : you are trying to assing char[10] with char* which is not possible

&strTo[0] = str_copy(strFrom, strTo);

But it's not usefull since the copy is done inside

In ur code, after calling str_copy() function:

char *strFinal = str_copy(strFrom, strTo);

strFinal points to the '\0', which is at the end of "abc123".

strTo in main() function can display correctly, because it is not THE SAME strTo in str_copy() function, but points to strTo[10]. strTo in str_copy() still points to the terminating zero.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top