I am passing 3 pointers (key, K1Ptr, K2Ptr) as arguments to a function (keyGenerator) but when the function call ends, only the key pointer keeps the value from the function call and the other 2 pointers don't.
I have tried a lot of different things, like returning an array with the 2 pointers, or i tried not using pointers and pass 2 arrays instead. Both tries had the same result none kept value after the function call.
char K1[9], K2[9];
char *K1ptr, *K2ptr;
K1ptr = K1;
K2ptr = K2;
keyGenerator(key, K1ptr, K2ptr);
printf("Key. %s\n", key);
printf("K1. %s\n", K1Ptr);
printf("K2. %s\n", K2Ptr);
\
void keyGenerator(char *key, char *K1, char *K2) {
char P10_Left[6];
char P10_Right[6];
char *P10leftPtr, *P10rightPtr;
printf("Starting key: %s\n", key);
//P10 Operation first step
P10_swap(key);
printf("P10swap key: %s\n", key);
//Initializing the left and right arrays
int i;
for(i=0;i<5;i++) {
P10_Left[i] = key[i];
P10_Right[i] = key[i+5];
}
P10_Left[5] = '\0';
P10_Right[5] = '\0';
P10leftPtr = P10_Left;
P10rightPtr = P10_Right;
//The left half shift
LS(P10leftPtr, 1);
//The right half shift
LS(P10rightPtr, 1);
//P8 swap starts here
K1 = P8_swap(P10leftPtr, P10rightPtr);
printf("K1 key: %s\n", K1);
//P8 swap ends here
//After we find K1 we need to shift the 2 halves again, 2 times to the left this time
//The left half shift
LS(P10leftPtr, 2);
//The right half shift
LS(P10rightPtr, 2);
//After the 2 shifts we use P8 operation again on the new halves
//P8 swap starts here
K2 = P8_swap(P10leftPtr, P10rightPtr);
printf("K2 key: %s\n", K2);
//P8 swap ends here
} //
char* P8_swap(char *left_key, char *right_key) {
int P8[8] = {6, 3, 7, 4, 8, 5, 10, 9}; //key possitions after P8 operation
char P8_Output[9];
char *K1; //They key after the P8 swap
char keyLR[11]; //The left and right halves will be stored together here
int i;
//The two halves become one so that we can do the P8 swap
for(i=0;i<5;i++) {
keyLR[i] = left_key[i];
keyLR[i+5] = right_key[i];
}
//P8 swap
for(i=0; i<8; i++) {
P8_Output[i] = keyLR[P8[i]-1]; //P10[i] - 1 because the possitiongs in P10 are from 1-10 and not 0-9
}
P8_Output[8] = '\0';
K1 = P8_Output;
return K1;
}
After the function keyGenerator when i print the K1Ptr and K2Ptr i get nothing but i was expecting to get the values that are stored inside the function.
P8_swap()to your code ?P8_swapis wrong. You return a pointer toP8_Outputwhich is a local variable. Never do that! When the function returns, the local variable is no longer present and the pointer points to illegal memory. If you really want something like that, you must use dynamic memory allocation.