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:36

>>24
That's not what strlen returns.

The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).

This should not be confused with the size of the array that holds the string. For example:

char mystr[100]="test string";

defines an array of characters with a size of 100 chars, but the C string with which mystr has been initialized has a length of only 11 characters. Therefore, while sizeof(mystr) evaluates to 100, strlen(mystr) returns 11.

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