0

I have an assignment and I am new to C. I will attach the assignment and my code. Basically, the issue is that my program doesn't work and I have no idea what's wrong.

Solve the following problem:

  • with pointers (pointer arithmetics instead of array[i]), but using your own user-defined functions

Write a program that reverses a string (array of char) entered by the user.

#include <stdio.h>
#include <conio.h>
void reversed_string(char *s,int nr)
{
    int i;
    for(i=nr; i>=0; i--)
    printf("%c",*(s+i));
}
int main()
{
    char *s;
    int nr;
    gets(s);
    nr=strlen(s);
    reversed_string(s,nr);
    return 0;
}
1
  • 2
    Please enable full compiler warnings. It tells you that s was uninitialised (has no memory allocation) and that gets() is undefined. Commented Dec 28, 2021 at 19:18

3 Answers 3

2

For starters the pointer s is uninitialized and has an indeterminate value

char *s;

So the call of the function gets that is unsafe (and the function is not supported by the C Standard)

gets(s);

invokes undefined behavior.

Instead you could write in main for example

char s[100];

fgets( s, sizeof( s ), stdin );

s[ strcspn( s, "\n" ) ] = '\0';

As for the function then take into account that to reverse a string does not mean to output a string in the reverse order. It means to change the string itself.

The function should be declared and defined the following way

char * reversed_string( char *s )
{
    if ( *s )
    {
        for ( char *first = s, *last = s + strlen( s ); first < --last; ++first )
        {
            char c = *first;
            *first = *last;
            *last = c;
        }
    }

    return s;
}

And in main the function is called like

puts( reversed_string( s ) );

Here is a demonstration program.

#include <stdio.h>
#include <string.h>

char * reversed_string( char *s )
{
    if ( *s )
    {
        for (char *first = s, *last = s + strlen( s ); first < --last; ++first)
        {
            char c = *first;
            *first = *last;
            *last = c;
        }
    }

    return s;
}

int main( void )
{
    enum { N = 100 };
    char s[N];

    printf( "Enter a string: " );

    fgets( s, sizeof( s ), stdin );

    s[strcspn( s, "\n" )] = '\0';

    puts( reversed_string( s ) );
}

If you may not use the standard string function strlen then the function reversed_string can look the following way

char * reversed_string( char *s )
{
    if ( *s )
    {
        char *last = s;

        while ( *last ) ++last;

        for (char *first = s; first < --last; ++first)
        {
            char c = *first;
            *first = *last;
            *last = c;
        }
    }

    return s;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Nice avoidance of the usual int vs. size_t issue.
Wow. Thank you so much, your advice was so useful! I really appreciate it.
1
  1. You read outside the string bounds.
  2. Use the correct type for sizes (size_t)
  3. Name functions non-confusing way. Your function is printing string in reverse order, not reversing the string.
  4. You use not initialized pointer
  5. Do not use gets
void print_reversed(const char *str, size_t nr)
{
    if(str && *str)
        do{
            putchar(*(str + nr -1));
        }while(nr--);
}

int main()
{
    char *s = "Hello World!";
    size_t nr;
    nr=strlen(s);
    print_reversed(s,nr);
    return 0;
}

If you want to reverse the string:

char *reverseString(char *str)
{
    char *end = str, *wrk = str;
    if(str && *str)
    {
        while(*(end + 1)) end++;
        while(end > wrk)
        {
            char temp = *wrk;
            *wrk++ = *end;
            *end-- = temp;
        }
    }
    return str;
}



int main()
{
    char s[] = "Hello World!";

    printf("Reversed string: `%s`\n", reverseString(s));
}

Comments

0

I would like to add one more point about Performance to above mentioned great answer.
From @Vlad from Moscow,Thus by making a program more efficient through using a macro for swapping.

Note: Bitwise xor operation used for swapping suppose a=4 b=5.
The binary representation of last four bits is followed.
0100 ^ 0101 = 0001 -> a == 1

0001 ^ 0101 = 0100 -> b == 4

0001 ^ 0100 = 0101 -> a == 5

#define SWAP(a,b){ \
    a=a^b;\
    b=a^b;\
    a=a^b;\
}
char * reversed_string( char *s )
{
    if ( *s )
    {
        for (char *first = s, *last = s + strlen( s ); first < --last; ++first)
        {
           SWAP(*first,*last);
        }
    }

    return s;
}

int main( void )
{
    enum { N = 100 };
    char s[N];

    printf( "Enter a string: " );

    fgets( s, sizeof( s ), stdin );

    s[strcspn( s, "\n" )] = '\0';

    puts( reversed_string( s ) );
}

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.