gpt4 book ai didi

c - 试图在 C 中打印一个结构数组

转载 作者:太空宇宙 更新时间:2023-11-04 04:22:33 26 4
gpt4 key购买 nike

我被要求构建一个函数,该函数接收一个包含大量零的静态二维数组并将其转换为一个结构数组。每个结构包含非零值和列的索引。
Pic for easy understanding

现在我已经构建了它,但问题在于打印功能。

1) 当我尝试打印两次时,它只打印了一次,第二次列表变为 NULL。为什么会出现这种情况?

    print(list);  
print(list);

2) 为什么我不能像在 main 函数中那样打印?

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;
}

关于c - 试图在 C 中打印一个结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45108044/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com