简体   繁体   中英

Reversing a string using two pointers in C

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);
 }

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. Eg 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

#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);

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);


}

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM