Transposition Cypher

This is the description for my computer science project:
For this transposition cypher you will separate the string into two different groups. The first group is composed of all the characters at even numbered indexes from the original string, and the second is composed of all the characters at odd numbered indexes. The final encrypted string is then all of the characters from the first group followed by all the characters from the second group.

This is the code I wrote and it isn't working like I thought it would. Why is this?
char *encryption(char *array, size_t size){
for(int i = 0; i < size; i++){
if(i % 2 == 0){
array[i] = array[i];
}
else{
array[(size / 2) + i] = array[i];
}
}
return array;
}
first, the data pointed to by pointers isn't protected. so if you change array[I] you changed the original.

second, ... play computer with it. for I = ...
0 .. array = abcde (a moves to a, ok)
1 .. array = abcbe (d is now lost forever)
and from there it just corrupts.

the right thing to do here is probably to make a new string.

there is probably a simple way to loop over 50% of the string and set
for(I=0 j=1 ... I+=2, j+=2)
newstring[I] = array[I];
newstring[j] = array[I+1]; //where j is the offset for the second half

without all the if then else modulo stuff. Its not wrong, but its probably unnecessary.

Last edited on
So I tried to do the program with a new string and it still didn't work. I tried to do the string with looping over half of it but I kept getting errors for my setup of the for loop.

char *encryption(char *array, size_t size){
char new_array[size];
int i;
for(i = 0; i < size; i++){
if(i % 2 == 0){
new_array[i] = array[i];
}
else{
new_array[size / 2] = array[i];
}
}
array = new_array;
return array;
}

are you allowed to use actual C++ classes like std::string? Just tons of possible pitfalls with your C-style method, and you need to manage memory manually.

It can probably be solved in a line or two if you were to use C++
Topic archived. No new replies allowed.