Mailbox #2: String Reverse and Array Bound Checking

Query: How to reverse a string without using any variable. You are not even allowed to use a variable to store a string.

There has to be some temporary variables to be used, for looping over the string.
Reversing a string requires swapping first character with the last, second with second last, third with third last and so on. Now the problem requires the string to be reversed in place (without using any other buffer to store the reversed string). So, we will have to interchange the elements in the original string buffer itself. Following is a pseudo code for the same.

i = 0;
j = StringLength – 1;
while (i < j) { Swap i and j element of String ++i; --j; }

The swapping of the two elements can be done either using a temporary variable or using XOR operator.

Query: ā€œCā€ doesnt provide boundation checking on array but it is still able to findout the length of array using the sizeof(). Why it cannot enforce boundation checking on array?

The reason why C is able to find out the length of array is because the length of array is part of its type declaration. As the type of a variable is known at compile time, sizeof operator can be used to find the length of array.
Faster execution speed would be one reason why C don’t do array bound checking.

2 Responses to “Mailbox #2: String Reverse and Array Bound Checking

Leave a Reply