0

What are the bugs in this function?

#include <string.h> #include <stdlib.h> char *reverse(char *input) { int len = strlen(input); char output[len]; for (int i = 0; i < len; i++) { output [len - i - 1] = input[i]; } return output; }

12th Dec 2021, 1:08 PM
Rose Candy
2 odpowiedzi
+ 5
Rose Candy , this looks very much like a homework or something like this. please do a try by yourself first. thanks for your understanding!
12th Dec 2021, 1:17 PM
Lothar
Lothar - avatar
+ 2
Lets look at this: char *reverse(char *input) { int len = strlen(input); char output[len]; for (int i = 0; i < len; i++) { output [len - i - 1] = input[i]; } return output; } Lets use "Hello" for the input len now = 5 output = memory-location 1, 2, 3, 4, 5 (named output[0], output[1], ect) probably filled with garbage values __ __ __ __ __ |__| |__| |__| |__| |__| << 5 memory locations for output within the scope of the for: i = 0 initialized; Going to test if i less than 5; then increment i each iteration; first pass: output[5 - 0 - 1] (this is equal to 4) becomes input[0] __ __ __ __ __ |__| |__| |__| |__ | |H | pass two, three, four and five will result in: __ __ __ __ __ |o | |l | |l | |e | |H | You want to end strings with a '\0' terminating char. 1. How will you add that? 2. Your current array cannot handle it
12th Dec 2021, 3:15 PM
William Owens
William Owens - avatar