Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing a array of character in its own place

Tags:

c

string

pointers

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?

like image 750
kTiwari Avatar asked Aug 29 '12 13:08

kTiwari


People also ask

How do you reverse an array without creating another array?

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 .

How do you reverse an array with a temporary variable?

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.


1 Answers

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 declaration
char 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 to
char s[] = { 'a', 'b', 'c', '\0' }, t[] = { 'a', 'b', 'c' };
The contents of the arrays are modifiable.

On the other hand, the declaration
char *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 use p 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.

like image 50
perilbrain Avatar answered Oct 12 '22 06:10

perilbrain