Hi,

I try to add some data to linked list and print it but it doesn't stop printing.. Can you assist please?

This is the code:

main:

Code:

void third_main(){
int** arr;
index_s* ans_arr;
int rows, cols;
int num_of_sums;
node_s* head = NULL;
printf("Enter number of rows: ");
scanf("%d",&rows);
printf("Enter number of cols: ");
scanf("%d",&cols);
arr = alloc_matrix(rows, cols);
num_of_sums = index_sum(arr, rows, cols, &ans_arr, &head);
int i;
for(i=0; i<num_of_sums; i++){
printf("i=%d\t j=%d\t value=%d\n", (ans_arr)[i].i_index, (ans_arr)[i].j_index, (ans_arr)[i].value);
}
printf("\n\nLinked list print:\n");
print_list(head);
}

index sum:

Code:

int index_sum(int** arr, int rows, int cols, index_s** ans_arr, node_s** headRef){
int i;
int j;
int ans = 0;
int arr_i = 0;
for(i=0; i<rows; i++){
for(j=0; j<cols; j++){
if ((i+j) == arr[i][j]){
ans++;
}
}
}
*ans_arr = (index_s*)malloc(ans*sizeof(index_s));
for(i=0; i<rows; i++){
for(j=0; j<cols; j++){
if((i+j) == arr[i][j]){
(*ans_arr)[arr_i].i_index = i;
(*ans_arr)[arr_i].j_index = j;
(*ans_arr)[arr_i].value = arr[i][j];
arr_i++;
}
}
}
*headRef = malloc(sizeof(node_s));
for(i=0; i<ans; i++){
push(headRef, (*ans_arr)[i]);
}
return ans;
}

print list:

Code:

void print_list(node_s* headRef){
node_s* current = headRef;
while(current != NULL){
printf("%d %d %d", (*current).data.i_index);
}
}

push:

Code:

void push(node_s** headRef, index_s data){
node_s* newNode = malloc(sizeof(node_s));
newNode->data = data;
newNode->next = *headRef;
*headRef = newNode;
printf("%d", (*headRef).data.i_index);
}

structs:

Code:

typedef struct{
int i_index;
int j_index;
int value;
}index_s;
// struct of linked list Node
typedef struct node_s{
index_s data;
struct node_s* next;
}node_s;

Thanks