Home > OS >  3rd character of the string is not reversing the code given below
3rd character of the string is not reversing the code given below

Time:07-07

How can I assign third character to fourth character?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {

    char a[50];
    int i,l,temp;

    setbuf(stdout,NULL);
    printf("enter a string");

    scanf("%s",a);
    l=strlen(a);

    for(i=0;i<=l/2;i  ){
        temp=a[i];
        a[i]=a[l-i-1];
        a[l-i-1]=temp;
    }

    printf("%s",a);
    return EXIT_SUCCESS;
}

output:

enter a stringamalks

skalma

CodePudding user response:

Your immediate problem is that your loop is execuing one more time than you expect.

Assuming input is "amalks" .. and therefore l is 6

for(i=0;i<=l/2;i  )

goes

i = 0;                     // swap a and s
i = 1;                     // swap m and k
i = 2;                     // swap a and l
i = 3; // 3 <= 6/2         // swap l and a

CodePudding user response:

The reason of the problem is the incorrect condition in the for loop

for(i=0;i<=l/2;i  ){
        ^^^^^^

When l is an even number then you have that i will be equal to l / 2 and the expression a[l-i-1] will be equivalent to a[l-l / 2-1] that is the same as a[l /2 - 1].

Change teh condition of the loop the following way

for(i=0;i < l/2;i  ){
        ^^^^^^

Pay attention to that as the function strlen has the return size_t then the variables l and i also should have the type size_t.

Ans the call of scanf should look either like

scanf("Is",a);

or like

scanf("I[^\n]",a);

to avoid the array memory overflow.

  • Related