I am trying to reverse a string in C, I was able to accomplish this but not without a side effect that I don't quite understand. Here is my code to reverse a string:
void reverseString(char *toReverse, char *reverse) {
int i = strlen(toReverse);
int counter = 0;
for (i; toReverse[counter] != '\0'; i--) {
reverse[i] = toReverse[counter];
counter++;
}
}
int main(int argc, char *argv[]) {
char reverse[strlen(argv[1]) + 1];
reverse[strlen(reverse)] = '\0';
reverseString(argv[1], reverse);
printf("The reverse string is '%s'", reverse);
}
When give a string this correctly reverse the string but also adds some additional data, for example:
Given the string abc123
the string 321cbaub◄¥u"ñç«
is returned
Why is this happening and how can I fix it?