我被要求建立一个函数,它接收一个静态的二维数组,其中有很多零,并将其转换为一个结构数组。每个结构都包含不为零的值和列的索引。
现在我已经建立了它,但问题是打印功能。
1)当我尝试打印两次时,它只打印一次,第二次列表变为空。为什么会这样?

    print(list);
    print(list);

2)为什么我不能像在主功能中那样打印?
printf("this is just a print |%d||%d|  ", list[0]->next->next->next->data, list[0]->col);

为什么我不能访问它,程序崩溃了。。。
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
//#include <vld.h>
#include <string.h>
#include <ctype.h>
#define C 5
#define N 4

typedef struct Node {
    int data;
    int col;
    struct Node *next;
} node;

node **fun(int arr[N][C]) {
    int i, j, k;
    node **list;
    node *temp;

    list = (node**)calloc(N, sizeof(node *));

    for (i = 0; i < N; i++) {
        list[i] = NULL;
        for (j = C - 1; j >= 0; j--)
            if (arr[i][j] != 0) {
                temp = (node*)malloc(sizeof(node));
                temp->data = arr[i][j];
                temp->col = j;
                temp->next = list[i];
                list[i] = temp;
            }
    }
    return list;
}

void print(node **head) {
    int i;
    node **temp = head;
    for (i = 0; i < N; i++) {
        while (temp[i]) {
            printf("|%d||%d|  ", temp[i]->data, temp[i]->col);
            temp[i] = temp[i]->next;
        }
        printf("\n\n");
    }
}

void main() {
    int arr[N][C] = { {0,0,4,0,7}, {3,0,0,0,0}, {9,1,0,6,0} , {0,0,0,0,0} };
    node **list;
    list = fun(arr);

    print(list);  ///////////
    print(list);  ///////////////

    printf("this is just a print |%d||%d|  ", list[0]->next->next->next->data, list[0]->col);
}

最佳答案

如注释中所述,您正在打印指针列表的过程中销毁它们:

    while(temp[i])
    {   printf("|%d||%d|  ",temp[i]->data,temp[i]->col);
        temp[i]=temp[i]->next;    // <---- here
    }

每个temp[i]都与head[i]相同,因此您可以在执行此操作时修改原始列表。当这个值为NULL时,while循环退出,所以最终的结果是所有数组元素都为null。
您需要将此值分配给一个临时值,以便可以在不更改列表的情况下遍历列表:
    node *temp2 = temp[i];
    while(temp2)
    {   printf("|%d||%d|  ",temp2->data,temp2->col);
        temp2=temp2->next;
    }

10-07 18:57
查看更多