The strings contained in a character array cannot be copied by assigning one pointer to another. You need to use a function like strcpy
which searches the memory pointed to by the pointer until it reaches a null-terminator ('\0'
) and copies the content to a memory pointed to by the destination.
Example:
// Initialize an array of characters which contain the string "Foo bar\0";
char input[] = "Foo bar";
// Allocate a character array on the heap and assign it to the pointer pDest
char *pDest = new char[100];
// Reassign the pointer to the first element of input
pDest = input;
delete [] pDest; // Oops: Deleting the first element of input!
Instead, you should do this:
char input[] = "Foo bar";
char *pDest = new char[100];
// Copy all chars in the memory at input to the memory pointed to by pDest
strcpy(pDest, input);
delete [] pDest; // pDest still points to the dynamic memory, everything's fine
Please note that using strcpy can be dangerous, it simply copies all content it can find until it reaches the terminating null to the destination, it doesn't (cannot!) check if the destination is actually large enough. In your example you already avoid this by using strlen, which is fine. It's just the assignment which doesn't work the way you think.
Apart from this error, there are other things which can be improved in your code:
- There is no need to make any copies at all, use
getline
to get the user input, allocate a new array with strlen + 1
of this user input and you're done, you can pass both of these variables to reverseit (remember to add a '\0'
delimiter at the end of reverseit
.
- The temporary
char
in reverseit
is unnecessary, just assign inputString[i]
directly to outputString[k]
- You can put both
i
and k
in the for
declaration, no need to handle k
differently
cout
can handle strings in the form of char*
, you don't need a loop the write the result to the console, just write cout << outputString
Handling strings in C++ is made much easier with the std::string
class, however I guess this is some sort of homework and you have to stick to the basics.