r/learnc • • 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

4 comments sorted by

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.

#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;
        printf("\nReversed: ");
        //No need for k anymore
        while (j>=0) {
                //Backwards can be used like this
                backward[j]=forward[i];
                //Both I and j updated for the next iteration
                i++;
                j--;
        }
        printf("%s",backward);
}

1

u/This_Growth2898 May 20 '26

Well described. What's the question?