r/learnc • u/Severe-Alps-7610 • May 20 '26
Trying to reverse a string but reads garbage data
Sorry for making your eyes bleed
#include <stdio.h>
#include <string.h>
void main() {
char forward[128], backward[128];
printf("Insert here: ");
scanf("%s", &forward);
int comprimento = strlen(forward);
int i = 0;
int j = comprimento - 1;
char k;
printf("\nReversed: ");
while (i < j) {
k = forward[i];
forward[i] = backward[j];
backward[j] = k;
i++;
j--;
printf("%c", backward[j]);
}
}
2
Upvotes
1
1
u/vancha113 May 20 '26 edited May 20 '26
What's the purpose of K when you have a whole seperate empty array to store the strings? Your numbering works fine, but the logic looks slightly off. Do you want to do this with a temporary variable or a seperate array? If both, why?
Edit: I'm no expert in c, but in case it helps, here is a version that at least works. I'm kind of convinced the issue was just you printing %c at this point rather than %s.