Tom Clabault Tom Clabault - 1 month ago 7
C Question

C - Array content exchange

I'm actually trying, with a bi-dimensionnal array of string ( It could bi tri-dimensionnal in fact ), to exchange two "cells" of the array.

Before, i used memcpy but when comes long string, comes long execution time so I thought it was possible to simply exchange the pointers of the array but I don't know how to do :(

Here's my code:

#include <stdio.h>
#include <stdlib.h>

void fonction(unsigned char*** tab);

int main()
{
unsigned char*** tab;
tab = malloc(sizeof(unsigned char**) * 3);
if (tab == NULL)
exit(0);

for (int line = 0; line < 3; line++)
tab[line] = malloc(sizeof(unsigned char*) * 3);

for (int line = 0; line < 3; line++)
for (int column = 0; column < 3; column++)
tab[line][column] = malloc(sizeof(unsigned char) * 5);


for (int line = 0; line < 3; line++)
for (int column = 0; column < 3; column++)
for (int cell = 0;cell < 5;cell++)
tab[line][column][cell] = line * 3 * 5 + column * 5 + cell;



for (int i = 0;i < 32;i++)
fonction(tab);

for (int line = 0; line < 3; line++)
for (int column = 0; column < 3; column++)
free(tab[line][column]);

for (int line = 0; line < 3; line++)
free(tab[line]);

free(tab);

return 0;
}

void fonction(unsigned char*** tab)
{
unsigned char temp[5] = { 0, 0, 0, 0, 0 };

int alea = 0;
int alea2 = 0;
int alea3 = 0;
int alea4 = 0;

srand(58);

for (int line = 0; line < 3; line++)
{
for (int column = 0; column < 3; column++)
{
alea = rand() % 3;
alea2 = rand() % 3;
alea3 = rand() % 3;
alea4 = rand() % 3;

*temp = tab[alea][alea2];
tab[alea][alea2] = tab[alea3][alea4];
tab[alea3][alea4] = *temp;
}
}
}


Errors come when freeing tab and this is expectable because fonction does any old thing :)

Thanks in advance !

Answer Source

I am not sure why you are using

   unsigned char temp[5] = { 0, 0, 0, 0, 0 };

Just use

    char* temp;

And do swapping as

        temp = tab[alea][alea2];
        tab[alea][alea2] = tab[alea3][alea4];
        tab[alea3][alea4] = temp;