2

I'm trying to reverse a string using pointers sptr1 and sptr2, The len gives the correct length of the entered string but the string is not reversed and str1 is not displaying on my terminal. Please provide some insights

#include<stdio.h>
void main()
{
 char str1[10];
 char temp;

 char *sptr1;
 char *sptr2;
 int len;
 printf("Enter a string:");
 scanf("%s",&str1);
 sptr1=str1;
 sptr2=str1;
 while(*sptr1!='\0')
 {
  sptr1++;
 }
 len=sptr1-str1;
 printf("Length of the string:%d",len);

 while(len!=0)
 {
  temp=*sptr1;
  *sptr1=*sptr2;
  *sptr2=temp;

  sptr1--;
  sptr2++;
  len=len-1;
 }
  printf("%s",str1);
 }
random temp
  • 31
  • 2
  • 8

4 Answers4

3

After while(*sptr1!='\0')... sptr points to the null-terminator of the string and then you are switching this null terminator with the first character. E.g. you move the null terminator to index 0. You have to decrement sptr before starting the reverse.

You should also decrement len by 2, otherwise you would iterate over the whole array and switch the already switched characters back.

Some other small mistakes:
main should return int, not void.
scanf("%s", &str1); should be scanf("%s", str1);, str1 already decays to a pointer.
You should add \n in your printf statements to have the output in different lines instead of 1 long line.

#include<stdio.h>

int main() {
    char str1[10];
    char temp;
    
    char *sptr1;
    char *sptr2;
    
    int len;
    printf("Enter a string:\n");
    scanf("%s", str1);
    sptr1 = str1;
    sptr2 = str1;
    
    while ( *sptr1 != '\0') {
        sptr1++;
    }
    
    len = sptr1 - str1;
    printf("Length of the string:%d\n", len);
    sptr1--;
    
    while (len > 0) {
        temp = *sptr1;
        *sptr1 = *sptr2;
        *sptr2 = temp;

        sptr1--;
        sptr2++;
        len = len-2;
    }
    printf("%s\n", str1);
}

See it live: https://ideone.com/WAnQLi

Santosh Kumar
  • 26,475
  • 20
  • 67
  • 118
mch
  • 9,424
  • 2
  • 28
  • 42
  • yes sir , thank you! i will check with various other examples and types – random temp Nov 12 '18 at 11:12
  • Sir , can you please explain why it is len=len-2 ? – random temp Nov 12 '18 at 11:14
  • run this code for "aiaz" , its not showing exact reverse. I think the while should be changed to (len>0) – random temp Nov 12 '18 at 11:18
  • You are right, changed to `len>0`. You only have to iterate over half of the array. Think about the input `abcd`: You switch `a` and `d`, `b` and `c` (here you would be done), but when you iterate over the whole array you switch also `b` and `c`, `a` and `d` again and you get the original string again. – mch Nov 12 '18 at 11:26
0
#include<stdio.h>
#include<string.h>
int main(int argc, const char * argv[])
    {
        char s[]="hello";
        strrev(s);
        puts(s);
        return 0;
    }

try strrev function:

char *strrev(char *str);
myhaspldeep
  • 226
  • 2
  • 7
0

there is only one mistake @mch's code in

len = len - 2;

because of this, program won’t work for string which length is even number correctly. I write to code because of more readability.

#include <stdio.h>


int main()
{
    char str[10];
    printf("Enter a string:\n");
    scanf("%s", str);
    char *ptr1, *ptr2;
    ptr1 = ptr2 = str;
    size_t len = 0;

    while (*ptr1) {
       ++ptr1, ++len;
    }
    printf("Length of the string:%u\n", len);

    for (int k = 0; k < len / 2; ++k) {
        char temp = *(--ptr1);
        *ptr1 = *ptr2;
        *ptr2++ = temp;

    }

    printf("%s\n", str);


}
User8500049
  • 410
  • 3
  • 12
0

Just an additional answer, be very careful with buffer overflow issues. Also a minor detail, you don't really need a len variable.

Below a commented code showing a way to deal carefully with memory writing.

#include <stdio.h>

// Here a way to use constants both as integer and strings
// See https://stackoverflow.com/questions/5459868
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)

// Let's define a max length
#define MAX_STRING_LENGTH 10

void main()
{
  char sptr[MAX_STRING_LENGTH + 1]; 

  char *sptr1=sptr,*sptr2=sptr;
  char swap;

  printf("Enter a string (" STR(MAX_STRING_LENGTH) " at most): ");

  // Here, limit the input to sptr size - 1
  // (let the last index for the null character)
  // Example : "%10s" means "at most 10 characters, additional ones
  //           will be removed."
  scanf("%" STR(MAX_STRING_LENGTH) "s",&sptr);

  // Finding the last character BEFORE the NULL character
  while(*(sptr2+1) != '\0') sptr2++;

  // Swaping
  while (sptr2 > sptr1)
    {
      printf("\t-> swaping %c <-> %c\n", *sptr1, *sptr2);
      swap=*sptr1;
      *sptr1=*sptr2;
      *sptr2=swap;
      sptr1++,sptr2--;
    }

  printf("Result : [%s]\n",sptr);
}

Examples (strings with odd and even length):

user:~$ ./a.out 
Enter a string (10 at most): abc
        -> swaping a <-> c
Result : [cba]
user:~$ ./a.out 
Enter a string (10 at most): abcd
        -> swaping a <-> d
        -> swaping b <-> c
Result : [dcba]
user:~$ ./a.out
Enter a string (10 at most): abcdefghijklmnopqrstuvwxyz
        -> swaping a <-> j
        -> swaping b <-> i
        -> swaping c <-> h
        -> swaping d <-> g
        -> swaping e <-> f
Result : [jihgfedcba]
Amessihel
  • 5,891
  • 3
  • 16
  • 40