I am having trouble copying a 2D array in a function in c. Here is the code:
void Add(Lista* list,int** estado, char* sec, int size)
{
if(list->last==NULL)
{
list->last = calloc(1,sizeof(element));
list->last-> secuencia = sec;
list->last->next = NULL;
list->last->prev = NULL;
list->last-> estado = (int**)calloc(size,sizeof(int));
memcpy(&list->last->estado,&estado,size*sizeof(int));
list->cantidad++;
}
else
{
list->last-> next = calloc(1,sizeof(element));
list->last-> next -> secuencia = sec;
list->last->next->next = NULL;
list->last->next->prev = list->last;
list->last =list->last->next;
list->last->estado = (int**)calloc(size,sizeof(int));
memcpy(&list->last->estado,&estado,size*sizeof(int));
list->cantidad++;
}
}
Here are the structs Lista and element
typedef struct element
{
char* secuencia;
struct element* next;
struct element* prev;
int** estado;
}element;
typedef struct Lista
{
int cantidad;
element* last;
}Lista;
The idea is to add "elements" in Lista, it is a basic list that returns the last added element. The problem is that every element stored in list returns the same "estado" (2D int array), if I modify one of the elements estado then every element estado gets the same modification. So, I dont know where is the problem, because memcpy() should copy the values and then make both arrays independent of each other, right?.
PS: Sorry if it was not well explained, I speak Spanish
EDIT
So, I change my code based on the answers to this:
void Add(Lista* list,int** estado, char* sec, int size)
{
if(list->last==NULL)
{
list->last = calloc(1,sizeof(element));
list->last-> secuencia = sec;
list->last->next = NULL;
list->last->prev = NULL;
list->last-> estado = (int**)calloc(size,sizeof(int));
memcpy(list->last->estado,estado,size*sizeof(int));
list->cantidad++;
}
else
{
list->last-> next = calloc(1,sizeof(element));
list->last-> next -> secuencia = sec;
list->last->next->next = NULL;
list->last->next->prev = list->last;
list->last =list->last->next;
list->last->estado = (int**)calloc(size,sizeof(int));
memcpy(list->last->estado,estado,size*sizeof(int));
list->cantidad++;
}
}
Now I haven't valgrind errors, but I keep getting the problem (when I modify one array the others get the modification)
EDIT2
So, I started checking the code and before the call to Add() there was an incorrect assignation of the array (always passed the same array to the function), that and the modification of EDIT1 solved my problem.
PS2: I will look deeply into pointer, thanks