Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C reversing a string

Name: Anonymous 2012-10-29 12:00

Why does "printf("%c, reverse")" just put out "aggiN", but ("%s, reverse") outside of the loop put out "aggiNNigga" when it should do the same?

int main(int argc , char* argv [ ] ) {

    int i=0;
    int c;
    int a=0;
    char string[]="Nigga";
    char reverse[20];

    i=sizeof(string);
    printf("%d\n", (i-1));

        for(c=i-2;c>=0;c--)
        {
            reverse[a]=string[c];
                        printf("%c", reverse[a]);
                        a++;

        }
    printf("\n%s", reverse);
    return 0;
}

Name: Anonymous 2012-10-29 18:30

>>21
The size is the one as reported by strlen(in), so it shouldn't segfault. Mayhaps a better idea would be

void reverse(char* in, char* out) {
    int sz = strlen(in);
    out[size] = 0;
    rev(in, out+size-1);
}


But this wouldn't exactly be ideal, in my opinion.

You're right about the stack thing, though, it's completely unnecessary. I forgot, is TCO a thing in C compilers or is gcc the only one that supports it?

void rev(char* in, char* out) {
    for (;;) {
        *out = *in;
        if (*in) { in++; out--; }
        else { return; }
    }
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List