Search code examples
creversec-stringsstrlenfunction-definition

Print pointer string which is return from function in C


Trying to write a C program to reverse the given string (using Pointer) and here is the code.

[sample.c]

#include <stdio.h>
#include <stdlib.h>

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

char *_reverse(char s[])
{
    int len = _len(s);
    char *r = malloc(len * sizeof(char));
    for (int i=len-1; i >= 0; i--) {
        *r++ = s[i];
    }

    *r = '\0';  // Line 21
    r -= len;   // Line 22
    return r;
}

int main(int argc, char *argv[])
{

    char s[10] = "Hello";
    printf("Actual String: %s\n", s);
    printf("Reversed: %s\n", _reverse(s));
    return 0;
}

Current O/P:

Actual String: Hello

Reversed: (null)

Expected O/P:

Actual String: Hello

Reversed: olleH

What is wrong or missing in here..? Please correct me. Thanks in advance.


Solution

  • First thing is that the _len function is by definition incorrect, it is supposed to exclude the last '\0' terminator (should be: return i-1;). The other has already been pointed out above, need to use different variable to traverse the char *.

    #include <stdio.h>
    #include <stdlib.h>
    
    int _len(char s[]) {
        int i = 0;
        while (s[i++] != '\0');
        return i-1;
    }
    
    char *_reverse(char s[]) {
        int len = _len(s);
        //printf("Len: %d\n", len);
        char *r =  (char *) malloc((len+1) * sizeof(char));
        char *ptr = r;
        for (int i=len-1; i >= 0; i--) {
            //printf("%d %c\n", i, s[i]);
            *(ptr++) = s[i];
        }
        *(ptr++) = '\0';
        return r;
    }
    
    int main(int argc, char *argv[]) {
        char s[10] = "Hello";
        printf("Actual String: %s\n", s);
        printf("Reversed: %s\n", _reverse(s));
        return 0;
    }
    
    Actual String: Hello
    Reversed: olleH