0

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.

4
  • 1
    You didn't add a '\0' to the end of the char array Commented Dec 4, 2020 at 17:00
  • @pavi2410 Same result after adding *r = '\0' before of return statement in the function Commented Dec 4, 2020 at 17:02
  • stackoverflow.com/q/36965437/7595401 Commented Dec 4, 2020 at 17:06
  • Do not use underscores in naming of functions or variables. It is a) not allowed by C standard b) Does not add anything to the code (and only reducing the readability) Commented Dec 4, 2020 at 17:07

4 Answers 4

3

You are modifying the pointer "r" of your newly allocated memory. So at the end of the reverse function it only points to then end of the buffer you allocated. You can move it back to the beginning by doing:

r -= len;

But to simplify things I'd recommend leaving r at the start using i and len to compute the index.

Also, you don't terminate the reversed string with a '\0'.

Sign up to request clarification or add additional context in comments.

1 Comment

Added (Pl check 'Line 22').. Still same results.
2

You increase r in the loop, then return it. Obviously, it points to an address after the actual reversed string. Copy r to another variable after malloc and return that.

Comments

0

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

1 Comment

Thank you, Fixed now. (_len() function is a big mistake) & just for an extra note that instead of declaring another one pointer (i.e, *ptr), as @Julien said adding r -= len; also working perfectly.. Thanks again.
0

The first function implementation

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

though has no standard behavior and declaration nevertheless is more or less correct. Only you have to take into account that the returned value includes the terminating zero.

As a result this memory allocation

char *r = malloc(len * sizeof(char));

is correct.

However the initial value of the variable i in the for loop

for (int i=len-1; i >= 0; i--) {

is incorrect because the index expression len - 1 points to the terminating zero of the source string that will be written in the first position of the new string. As a result the new array will contain an empty string.

On the other hand, this function definition (that you showed in your post after updating it)

int _len(char s[])
{
    int i = 0;
    while (s[i++] != '\0');
    // return i;              // Old code
    return i == 0 ? i : i-1;  // Line 9 (Corrected)
}

does not make a great sense because i never can be equal to 0 due to the prost-increment operator in the while loop. And moreover now the memory allocation

char *r = malloc(len * sizeof(char));

is incorrect. There is no space for the terminating zero character '\0'.

Also it is a bad idea to prefix identifiers with an underscore. Such names can be reserved by the system.

The function can be declared and defined the following way

size_t len( const char *s )
{
    size_t n = 0;

    while ( s[n] ) ++n;

    return n;
}

To reverse a string there is no need to allocate memory/ If you want to create a new string and copy the source string in the reverse order then the function must be declared like

char * reverse( const char * s );

that is the parameter shall have the qualifier const. Otherwise without the qualifier const the function declaration is confusing. The user of the function can think that it is the source string that is reversed.

So if the function is declared like

char * reverse( char *s );

then it can be defined the following way.

char * reverse( char *s )
{
    for ( size_t i = 0, n = len( s ); i < n / 2; i++ )
    {
        char c = s[i];
        s[i] = s[n - i - 1];
        s[n - i - 1] = c;
    }

    return s;
} 

If you want to create a new string from the source string in the reverse order then the function can look like

char * reverse_copy( const char *s )
{
    size_t n = len( s );

    char *result = malloc( len + 1 );

    if ( result != NULL )
    {
        size_t i = 0;

        while ( n != 0 )
        {
            result[i++] = s[--n];
        }

        result[i] = '\0';
    }

    return result;
}

And you should not forget to free the result array in main when it is not needed any more.

For example

char s[10] = "Hello";
printf("Actual String: %s\n", s);

char *t = reverse_copy( s );
printf("Reversed: %s\n", _reverse(t));
free( t );

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

If you want to define the functions without using the subscript operator and index variables then the functions len and reverse_copy can look the following way

size_t len( const char *s )
{
    const char *p = s;

    while (*p) ++p;

    return p - s;
}

char * reverse_copy( const char *s )
{
    size_t n = len( s );

    char *p = malloc( n + 1 );

    if (p)
    {
        p += n;
        *p = '\0';

        while (*s) *--p = *s++;
    }

    return p;
}

And pay attention to that my answer is the best answer.:)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.