-1

So I am writing a program that will encrypt a 2D array of chars in a function by passing a 2d array to it, but I am struggling to return it to main so I can use it other functions such as encrypt again to encrypt it twice.

char *encrypt(char bob[6][6], int key[6])[6][6]
{
int i ,j;
char tempArr[6][6];
printf("\n");
for (i = 0; i < 6; i++) {

    for (j = 0; j < 6; j++)
    {
        int col = key[j];
        printf("%c", bob[i][col]);
         tempArr[i][j] = bob[i][col];
    }

    printf("\n");
}
for (i = 0; i < 6; i++) {
    for (j = 0; j < 6; j++)
    {
        printf("%c", tempArr[j][i]);
    }
    printf(" ");
}

return tempArr;

}

this is my encrypt function that I am trying to return a string/2d array from **tempArr = encrypt(bob, key); encrypt(tempArr, key); and this is how I am passing the data through to that function

1 Answers1

0

You are returning local variable from a function, which is destroyed by the ond of the function. You have to allocate it dynamically, using malloc(). You can do it like this: char **tempArr = malloc(6 * sizeof(char *)); for (i=0; i<6; i++) tempArr[i] = malloc(6 * sizeof(char)); This will dynamically allocate space for 6x6 array of chars. Don't forget to free() it when you are done with it.

Honza Dejdar
  • 947
  • 7
  • 19