while loop - Why does this index work? c++ -
all, professor gave following loop use in weeks assignment:
char *ptr1, *ptr2; char c; ptr1 = &arr[0]; ptr2 = &arr[idx-1]; while(ptr1 < ptr2){ c = *ptr1; *ptr1 = *ptr2; *ptr2 = c; ptr1++; ptr2--; }
is position of ptr1 vs. ptr2? program reverses c_str , works fine, don't understand why.
do have problem understanding of individual statements? if not, seeing how works question of going through steps.
the first 3 statements of loop swap character pointed ptr1
, 1 pointed ptr2
. initially, ptr1
, ptr2
point first , last characters of string. second pass, pointing second , second-last characters of string, etc.
initially:
+-----+-----+-----+-----+-----+-----+ +-----+ arr --> | | b | c | d | e | nul | c | ? | +-----+-----+-----+-----+-----+-----+ +-----+ ^ ^ | | ptr1 ptr2
after c = *ptr1;
:
+-----+-----+-----+-----+-----+-----+ +-----+ arr --> | | b | c | d | e | nul | c | | +-----+-----+-----+-----+-----+-----+ +-----+ ^ ^ | | ptr1 ptr2
after *ptr1 = *ptr2;
:
+-----+-----+-----+-----+-----+-----+ +-----+ arr --> | e | b | c | d | e | nul | c | | +-----+-----+-----+-----+-----+-----+ +-----+ ^ ^ | | ptr1 ptr2
after *ptr2 = c;
:
+-----+-----+-----+-----+-----+-----+ +-----+ arr --> | e | b | c | d | | nul | c | | +-----+-----+-----+-----+-----+-----+ +-----+ ^ ^ | | ptr1 ptr2
after ptr1++; ptr2--;
:
+-----+-----+-----+-----+-----+-----+ +-----+ arr --> | e | b | c | d | | nul | c | | +-----+-----+-----+-----+-----+-----+ +-----+ ^ ^ | | ptr1 ptr2
after pass:
+-----+-----+-----+-----+-----+-----+ +-----+ arr --> | e | d | c | b | | nul | c | b | +-----+-----+-----+-----+-----+-----+ +-----+ ^ ^ | | ptr1 ptr2
loop ends.
Comments
Post a Comment