简体   繁体   中英

Why is this program not stopping to take input?

I wrote a C program to reverse a string using pointers, the problem i am facing is that i am unable to accept the string without using loops. Neither is complete string printing, it's printing only single character.

I tried using loops to access the string and it works just fine but i don't intend to do that.

    #include<stdio.h>
    int main()
    {
      char s[10];
      char temp;
      scanf("%s", s);
      char *start=s;
      char *end=s;
      while(*end!='\0')
       {
        end++;
       }
        end--;
      while(start<end)
      {
        temp=*start;
        *start=*end;
        *end=temp;
      }
      printf("%s", s);
    }

The problem is that you never decrease the end pointer nor increase the start pointer in the second loop.

Try

while (start < end)
{
    temp = *start;
    *start++ = *end;
    *end-- = temp;
}

On the other hand, you can have problems if the user types nothing using your approach

while (*end != '\0')
{
    end++;
}
end--; // UB when strlen(s) = 0

switch to

if (*end != 0)
{
    end += strlen(s) - 1;
}

Also, it's a good idea to limit the string length when using scanf in order to avoid buffer overflows:

scanf("%9s", s);

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