[英]trying to print a array of structs in C
我被要求構建一個函數,該函數接收帶有很多零的靜態二維數組,並將其轉換為結構數組。 每個結構都包含不為零的值和該列的索引。
現在,我已經構建了它,但是問題出在打印功能上。
1)當我嘗試打印兩次時,它僅打印一次,而第二次列表變為NULL。 為什么會發生這種情況?
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;
}
您的print
函數會修改數組:它使用數組元素遍歷列表,並為它們保留NULL
值。
這是更正的版本:
void print(node **head) {
int i;
for (i = 0; i < N; i++) {
node *temp;
for (temp = head[i]; temp; temp = temp->next) {
printf("|%d||%d| ", temp->data, temp->col);
}
printf("\n\n");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.