Home > Enterprise >  unable to print string after reversing in C
unable to print string after reversing in C

Time:09-27

I have written below program to reverse the string, but it is not printed after reversal. What could be the issue?

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

main()
{
    char p[] = "krishna";
    
    strrv(p);
    printf("%s", p);    // -----> nothing prints here
}

void strrv(char p[])
{
    int l = strlen(p);
    int i=0;
    char tmp;
    
    
    while(i<l)
    {
        tmp = p[i];
        p[i] = p[l];
        p[l] = tmp;
        
        i  ;
        l--;
    }
}

CodePudding user response:

On the first loop iteration p[l] will refer to the terminating \0 of p which is then assigned to p[0] and that in turn that makes p an empty string. The fix is to initialize l to strlen(p) - 1 instead of strlen(p):

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

void strrv(char p[]) {
    for(int i = 0, l = strlen(p) - 1; i < l; i  , l--) {
        char tmp = p[i];
        p[i] = p[l];
        p[l] = tmp;
    }
}

int main() {
    char p[] = "krishna";
    strrv(p);
    printf("%s", p);
    return 0;
}

CodePudding user response:

int l = strlen(p);

This must be initialized with int strlen(p)-1, otherwise you move the final NUL '\0' (null character) on the first position.

  • Related