I'm working through "The C Programming Language" and trying to reverse a C-style string. My understanding is that a string literal like "voldemort" is represented as a character array (each of which has size 1) of 9 characters followed by a null character:
v o l d e m o r t \0
_ _ _ _ _ _ _ _ _ _
My idea to reverse the string is to find the length and then use that to declare an array of the appropriate length and define it as the reverse keeping a null at the end.
t r o m e d l o v \0
_ _ _ _ _ _ _ _ _ _
However, in my reversed string the length is suddenly longer and I'm not having any luck figuring out why.
#include <stdio.h>
int mystrlen(char s[]);
void reverse(char original[], char reversed[], int len);
int mystrlen(char s[]) {
int i = 0;
while (s[i] != '\0') {
++i;
}
return i;
}
void reverse(char original[], char reversed[], int len) {
int i, c;
for (i = 0; i < len; ++i) {
reversed[i] = original[len-i-1];
}
}
int main() {
int len;
char test[] = "voldemort";
len = mystrlen(test);
char tset[len+1];
reverse(test, tset, len);
printf("Original: %s\n", test);
printf("Original Length: %d\n", mystrlen(test)); // 9
printf("Original Size: %lu\n\n", sizeof(test)); // 10
printf("Reversed: %s\n", tset);
printf("Reversed Length: %d\n", mystrlen(tset)); // 13 (expected: 9)
printf("Reversed Size: %lu\n", sizeof(tset)); // 10
return 0;
}
Once you reverse the string need to NUL terminate
void reverse(char original[], char reversed[], int len) {
int i, c;
for (i = 0; i < len; ++i) {
reversed[i] = original[len-i-1];
}
reversed[i] = '\0'; //this line required
}
Output:
Original: voldemort
Original Length: 9
Original Size: 10
Reversed: tromedlov
Reversed Length: 9
Reversed Size: 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With