I want to pass liked list to function and create new list. I need some help to understand what I'm doing wrong. I create new pointer and copy the pointer to "curr" and than run on the list and built in. I try to find in which step I got it wrong . I already try to debug the program.
the struct is simple struct If i, j and the value of the matrix A are an arithmetic series they are added to the list.
int createList(int A[][COLS], list** lst, int rows, int cols)
{
// your code:
*lst = (list*)calloc(1, sizeof(list));
list* curr = *lst;
int i, j;
int counter = 0;
int d;
int check = 0;
int j_i;
int A_j;
four new_four;
for (i = 0; i < rows; i ) {
for (j = 0; j < cols; j ) {
j_i = j - i;
A_j = A[i][j] - j;
if (j_i == A_j) {
d = j-i;
new_four = createFour(i, j, d, A[i][j]);
if (counter == 0) {
curr = createElement(new_four);
}
counter ;
curr->next = createElement(new_four);
curr = curr->next;
}
}
}
curr->next = NULL;
return counter;
}
// create new object with all the parameters
four createFour(int i, int j, int d, int value)
{
four new_f;;
new_f.d = d;
new_f.i = i;
new_f.j = j;
new_f.value = value;
return new_f;
}
// create new Element with the data to the list
list* createElement(four data)
{
// your code:
list* new_Element = (list*)calloc(1, sizeof(list));
new_Element->data = data;
new_Element->next = (list*)calloc(1, sizeof(list));
return new_Element;
}
CodePudding user response:
The problem is that you're not actually passing back the list via the lst
parameter. You're allocating a value and storing it correctly, but then not using that value to add in all the data you want, because you never actually use it and instead create an entirely different list that is then causes a memory leak.
The problem boils down to this part
if (counter == 0) {
curr = createElement(new_four);
}
counter ;
curr->next = createElement(new_four);
curr = curr->next;
When counter
is 0, you create the start of a new list - this is the value you want to be storing into *lst
to pass back to the calling code.
You're also creating 2 nodes when I imagine you only want 1.
If you make this slight tweak, you'll get what you want.
if (counter == 0) {
*lst = curr = createElement(new_four);
} else {
curr->next = createElement(new_four);
curr = curr->next;
}
counter ;
you'll also need to remove this line at the start of the function as it isn't needed
*lst = (list*)calloc(1, sizeof(list));
and you don't need to assign *lst
to curr
here either since it is initiased later on
list* curr = *lst;