Mian Miftah Mian Miftah - 3 months ago 34
C Question

Reversing chars in C

I was looking at a function that reverses an array of

s and I get everything, but the one thing that confuses me is the last statement inside the last
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)

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

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;

Answer Source

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].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download