-2

Problem-To reverse a string using pointers, but my code instead of printing reversed string ,is printing the first letter of the string.

#include<stdio.h>

int main()
{
    int i;
    char n[100];
    char *ptr;
    ptr = n;
    char a[100];
    char *sptr;
    sptr = a;
    scanf("%s", n);

    for(i=0;n[i]!=0;i++)//Calculating the size of the string
        for(;(*sptr=*(ptr+i))!='\0';sptr++,ptr--)
        {
            ;
        }
    printf("%s",a);
    return 0;

}
6
  • 2
    "[c] string reversal" on this site will turn up a substantial number of hits. And no nested for loop is needed for this, so rethink your algorithm. Commented Feb 3, 2015 at 11:57
  • As it is you have a nested loop, i.e. the inner for loop which supposedly is meant to perform the reversal is nested within the loop calculating the string length. Is this intentional? Commented Feb 3, 2015 at 11:57
  • I am really not getting your program Commented Feb 3, 2015 at 11:59
  • No it is not intended to be nested,my approach was to just calculate length of the string using it. Commented Feb 3, 2015 at 11:59
  • possible duplicate of Reverse a string using pointers in a function, output in main is garbled Commented Feb 3, 2015 at 12:01

1 Answer 1

1

Your problem is twofold.

First, you're missing a ; after the first for loop.

for(i=0;n[i]!=0;i++); //note the ;

Secondly, you're array index used is out-of-bounds

for(;(*sptr=*(ptr+i))!='\0';sptr++,ptr--)

you need to reduce i once before using it.

you should write

for(;(*sptr=*(ptr+i-1))!='\0';sptr++,ptr--)

Note: IMHO, you're making a simple thing too complex. Think of an easier logic. There are many. for a live example, follow the link in the comments by Mr. WhozCraig.

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

1 Comment

Or just do this and forget all the indexes. That's what the pointers are for.

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.