kron maz
kron maz

Reputation: 131

Reversing chars in C

I was looking at a function that reverses an array of chars and I get everything, but the one thing that confuses me is the last statement inside the last for loop which is line[j] = temp;. I don't know what this is accomplishing.

    void reverse(char line[]) {

    char temp;
    int i, j;

    for (j = 0; line[j] != '\0'; ++j)
        ;
    --j;

    if (line[j] == '\n') {
        --j;
    }

    for (i = 0; i < j; ++i, --j) {
        temp = line[i];

        line[i] = line[j];

        //This statement is the one in which I dont understand it's function
        line[j] = temp;
    }
}

Upvotes: 2

Views: 82

Answers (2)

SAG
SAG

Reputation: 60

you simply want to exchange two variables inside an array together . you won't be able to just do line[i] = line[j]; because the i'th item of the 'line' array will be overwritten by the j'th variable and it's initial value will be lost. so, in order to avoid i'th item from being lost, you first copy it in the 'temp' (temp= line[i]) , you overwrite line[i] by line[j], then copy temp (which is your initial value of line[i])to line[j].

Upvotes: 3

Mureinik
Mureinik

Reputation: 311163

The last for run from i up and from j down until they meet in the middle, and switches those elements in the array. In each iteration of the loop, the ith item is saved to temp, the jth item is placed in the ith place, and then the previously saved value, temp, is assigned to the jth place.

Upvotes: 1

Related Questions