Something's wrong with my reverse string function

  • A+
Category:Languages

So it seems it works when I reversed "hello", but it prints out something weird like "ol▒eh" in the middle. It's gone when I fixed

i< length/2; 

to

i<= length/2; 

Isn't the first one supposed to be the right one? what's the ▒ character mean in C? is it something like Null?

void reverse_copy(char dest[], const char src[]){   size_t i;   char temp;   size_t length = (size_t)strlen(src);   for(i = 0; i <= length/2; i++){ /*?? why i<length/2 is not working*/     dest[i] = src[length-i-1];     temp = src[i];     dest[length-i-1] = temp;   } } 

 


The main problem with i< length/2; is that it may leave out the "middle" element in case of odd string lenght of src. Hence, the middle element in dest may remain uninitialized, showing up as some "arbitrary" ASCII value then.

But in general, your code is appropriate for reverse_in_place, where you have to take care of not overwriting something that you need later in the loop for copying.

If you do a reverse_copy, however, it is sufficient - or better - to simply have one reverse loop:

void reverse_copy(char dest[], const char src[]){   size_t i;   size_t length = strlen(src);   for(i = 0; i < length; i++){     dest[i] = src[length-i-1];   }   dest[i] = '/0'; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: