in the below program I need to reverse string without using library function. But the output after copying prints some garbage value. Can anyone kindly help me in figuring it out?

2 Answers
str1 and str2 must be char arrays large enough to hold the strings.
For your simplistic example, char str1[128], str2[128]; should do.
You must initialize j to the length of str1 before the loop and null terminate str2 with str2[j--] = '\0'; before the loop:
for (j = 0; str1[j] != '\0'; j++) {
continue;
}
str2[j--] = '\0';
for (i = 0; str1[i] != '\0'; i++, j--) {
str2[j] = str1[i];
}
4 Comments
Cherubim
but
strlen requires string.h library, OP wants to do without using itchqrlie
@ch3rub7: you are correct, I removed the
<string.h> dependency.divya
terminating str2 with null produces desired result. if str2 is not terminated with null, the output is like "ayvid garbage value divya"(as in output screen in pic one). I need to know how come after garbage value it prints the original string again at the end. Can anyone please clarify?
chqrlie
@divya: I'm not sure what code you are referring to: the code in the picture is broken, it should not compile. If you do not null terminate your string, the code invokes undefined behavior, leading to erratic behavior. A precise explanation for observed behavior in such circumstances is not very useful.
str2 should be assigned with null character '\0' after the string reversal in for loop.
for(j=strlen(str1);str1[i]!='\0';i++,j--)
str2[j-1]=str1[i];
str2[i]='\0';
1 Comment
divya
if str2 is not terminated with null, the output is like "ayvid garbage value divya"(as in output screen in pic one). I need to know how come after garbage value it prints the original string again at the end.
#include <stdio.h>at the top of the file. 2. Fix compiler errors. 3. If further questions, please copy/paste code as text, not images.#include, there should have been compile errors withstr1[i]andstr2[j]!!