vendredi 19 août 2016

Reverse string with pointers in C

I tried following two ways to reverse a string in C using char pointers:

Option 1:

void stringreverse(char *s){
    int n = stringlength(s) - 2;

    while(*s != '�'){
        char c = *s;
        *s = *(s+n);
        *(s+n) = c;
        s++;n--;
    }       
}

Option 2:

void stringreverse(char *s){
    char *p = s + stringlength(s) - 2;

    while(*s != '�'){
        char c = *s;
        *s = *p;
        *p = c;
        s++,p--;
    }   
}

None of the above works. Hints on why?

Aucun commentaire:

Enregistrer un commentaire