I have the following array in C (Used random names)
char * inputs[6] = {
"Kangaroo my shoe", "Fly high dragonfly",
"Philosophical Monkey", "Jumping Ape",
"Fearful lemurs", "Tall Giraffes"
};
The goal is to swap the first element by the next. As in to do this
char * inputs[6] = {
"Fly high dragonfly", "Kangaroo my shoe",
"Jumping Ape", "Philosophical Monkey",
"Tall Giraffes", "Fearful lemurs"
};
I have tried the following and some more.
ArrSwap(char *Arr[]){
int i;
for(i=0;i<6;i++){
void*temp = Arr[i];
Arr[i]=Arr[i+1];
Arr[i+1] = temp;
}
}
Thanks in advance! I've spent some hours trying to figure this out, each time I do it it ends up with a messed up order or not swapping any elements expect for the first and last.
There are two problems in your code -
ArrSwap()
you are looping over index 0 to 5. So, when i
becomes 5
, Arr[i+1]
points to Arr[6]
which leads to read from a memory past your array bounds. Which is undefined behavior.ArrSwap()
the loop needs to increment by 2 instead of 1.So the code may look like this after both issues are addressed -
void ArrSwap(char *Arr[]){
int i;
for(i=0; i<5; i+=2) {
char *temp = Arr[i];
Arr[i]=Arr[i+1];
Arr[i+1] = temp;
}
}
Notice there are following changes done in the ArrSwap()
function -
i < 6
to i < 5
(the reason mentioned in point 1 above). As ikegami mentioned, best practice would be to pass the array size as an argument (say n
) and use n - 1
in loop condition.char *
instead of void *
(The type of elements in Arr
is char *
)ArrSwap()
is mentioned as void
. With void
it is clearly conveyed that ArrSwap()
will not return anything.After fix the inputs
will be:
{"Fly high dragonfly", "Kangaroo my shoe", "Jumping Ape", "Philosophical Monkey", "Tall Giraffes", "Fearful lemurs"}