I'm passing two c-strings (one containing characters, the other one empty) to a function that is supposed to take the c-string that contains characters and populate the empty c-string with the string read from behind. Simple operation, but it doesn't work. I just can't figure out what I'm doing wrong.
#include <iostream>
#include <cstring>
using namespace std;
void magic(char*, const char*, int);
int main()
{
char string1[20];
char string2[] = "This is a test";
char *str1 = string1;
char *str2 = string2;
int stringsize = strlen(string2);
magic(str1, str2, stringsize);
return 0;
}
void magic(char* string1, const char* string2, int stringsize)
{
cout << string2 << endl; //here it prints as expected
*(string1 + stringsize) = '\0';
string1 = string1 + stringsize - 1;
for(;*string2 != '\0' ;string1--, string2++)
{
*string1 = *string2;
}
cout << string1 << endl; //blank space is printed - expected "This is a test" reversed
cout << string2 << endl; //blank space is printed - expected "This is a test"
}
str1andstr2variables, just pass the arrays as is to the function.char string1[20]it will still be a pointer. As for your problem, now might be a good time to learn how to use a debugger, because with a debugger you can step through code, line by line, and watch variables and their values and how they change. That will help you a lot with problems like this.magicfunction, why would you expectstring2to point to the beginning of the string when you are changing where it points to in the loop? That should give you a clue -- print the arrays aftermagicreturns.