I'm trying to reverse a string in C with following function:
void reverse(char *txt) {
char *copytxt;
copytxt = (char*) malloc((strlen(txt) + 1 ) * sizeof(char));
strcpy(copytxt, txt);
int i;
for(i=0;i<strlen(copytxt);i++){
if(i == strlen(copytxt)){
*(txt+i) = 0;
}
else{
*(txt+i) = *(copytxt+strlen(copytxt)-i-1);
}
}
}
When i print *(txt+i)
as a char in each loop of the for-loop. I'll get my reversed string.
But if i print the string txt
it just gives me nothing. Why is that? What am I doing wrong? Am I doing something wrong with the pointers?
By the way: I'm not allowed to use this notation: txt[1]
I hope you get my problem.
Thank you!