I was asked this question in an interview
I was supposed to reverse the array of character in its own place not to reverse the whole array of character.
if
char *ch="krishna is the best";
then I was supposed to reverse in such a way that the output should be like
anhsirk si eht tseb
I could not write the code in Interview .Can anyone suggest me how to write to do this.?
Can it be done with the help of pointers ?
if the interviewer had not told me to reverse it to its own place then would if be easy to deal with using another array of character of array,which would have the new character string after reversing it?
Steps to reverse an array without using another array in C:Set i=0 to point to the first element and j=length-1 to point to the last element of the array. Run while loop with the condition i<j . Inside loop swap ith and jth element in the array. Increment i and decrement j .
The temporary variable is for swapping: t=list[1]; list [1]=list[2]; list[2]=t; To reverse an array, swap the first and last elements (min and max), then the next-lowest (min+1, max-1) until min >= max.
Neither your interviewer can write a code for that.
char *ch="krishna is the best";
you cant change data in readonly part of memory and ch
points to a read only memory.
Update:- An Excerpt from N1548 (§6.7.9)
EXAMPLE 8
The declarationchar s[] = "abc", t[3] = "abc";
defines ‘‘plain’’ char array objects s and t whose elements are initialized with character string literals.
This declaration is identical tochar s[] = { 'a', 'b', 'c', '\0' },
t[] = { 'a', 'b', 'c' };
The contents of the arrays are modifiable.
On the other hand, the declarationchar *p = "abc";
defines p with type‘‘pointer to char’’
and initializes it to point to an object with type‘‘array of char’’
with length 4 whose elements are initialized with a character string literal. If an attempt is made to usep
to modify the contents of the array, the behavior is undefined.
You can see applying swapping on such data type is dangerous.
It is suggested to write code as:-
char ch[]="krishna is the best";
and then apply an XOR swap at every encounter of a space character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With