Trying to reverse a string without using string.h library functions in C using pointers

-2

It returns halfway and shows--Process returned -1073741819 (0xC0000005) This code shows no error or warning also. Just want to know exactly why is it happening?

#include<stdio.h>

void reverse(char*);

int main()
{
char str[200];
printf("Enter a string : ");
scanf("%s",&str);
reverse(str);
printf("Reversed string : %s",str);
}

void reverse(char *p)
{
char temp,*q;
*p=*q;
while(*p!='\0')
{
    q++;
}
while(p<q)
{
    temp=*p;
    *p=*q;
    *q=temp;
    p++;
    q--;
 }
}
c
string
pointers
reverse
asked on Stack Overflow Mar 31, 2021 by Mmehare

2 Answers

0

You never initialized q. It is pointing to something completely random.

Fix is char temp, *q = p;

answered on Stack Overflow Mar 31, 2021 by cchapin
0

Did the following changes as answered and added a change also which made the code work.

      #include<stdio.h>
      void reverse(char*);
      void main()
       {
         char str[20];
         printf("Enter a string : ");
         scanf("%s",&str);
         reverse(str);
         printf("Reversed string : %s",str);
        }
        void reverse(char *p)
        {
         char temp,*q=p;
         while(*q!='\0')
         {
           q++;
         }
         q--;
         while(p<q)
         {
          temp=*p;
          *p=*q;
          *q=temp;
           p++;
           q--;
         }
        }
answered on Stack Overflow Apr 2, 2021 by Mmehare

User contributions licensed under CC BY-SA 3.0