-3

I have searched and read just for days trying to resolve this issue.

I am simply trying to reverse a string in C using my own functions, but I am stumped now and haven't been able to move forward in 2 days!

Here is my code:

/*
This program takes a string
as input and returns it to
the user but in reverse order.
*/

#include "stdio.h"
#include "stdlib.h"
#define MAXLINE 1000

/* Take in a string and return its length. */
int getline(char s[]); 

/* Copy From to To. */
void copy(char To[], char From[]); 

/* Take the contents of a string and reverse them. */
char * reverse(char s[]);

int main() {

        char mainString[MAXLINE + 1];
        copy(mainString, "Test string.");

    printf("Your string before reversal: %s\n", mainString);
    reverse(mainString);
    printf("Your string after reversal: %s\n", mainString);

    return 0;
}


int getline(char s[]) {
    int i;
    for(i = 0; s[i] != '\0'; i++);
    i++;

    return i;
}

void copy (char To[], char From[]) {
    int i;
    for(i = 0; From[i] != '\0'; i++) {
        To[i] = From[i]; 
    }; 
    To[i] = '\0';
}


char * reverse(char s[]) {

    int string_length;
    string_length = getline(s);

    char myString[MAXLINE];
    int a = 0;

    int i;
    i = string_length;

    while (i >= 0) {
        s[i] = myString[a];
        a++;
        i--;
    };
    copy(s, myString);

    return s;
}
Marcassin
  • 1,386
  • 1
  • 11
  • 21
RHC4EVER
  • 43
  • 1
  • 1
  • 4

3 Answers3

2

Remove the i++ at the end of the getline function. This caused the returned string length to be 1 more than it should be, which in turn caused a '\0' to be the first char of your reversed string, which should not happen.

Moreover, the line

s[i] = myString[a];

is wrong. This changes s, but you want to change myString instead:

myString[i] = s[a];

(Alternatively, you could do copy(myString, s); before the while loop to fill myString and then copy data from there back to s in reverse.)

Daniel S.
  • 6,458
  • 4
  • 35
  • 78
1

Fix to

int getline(char s[]) {
    int i;
    for(i = 0; s[i] != '\0'; i++);
    return i;
}

char * reverse(char s[]) {
    int string_length;
    string_length = getline(s);
    char myString[MAXLINE];
    int i, a =0;
    i = string_length-1;
    while (i >= 0) {
        myString[a]=s[i];
        a++;
        i--;
    }
    myString[a] ='\0';
    copy(s, myString);

    return s;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
0

The reverse function expects to reverse the string s passed in parameter and myString is local string with junk characters

So you cannot do a

s[i] = myString[a]

You just loose all the characters in s

sethi
  • 1,869
  • 2
  • 17
  • 27