【发布时间】:2020-08-08 22:14:30
【问题描述】:
我正在尝试将数组转换为链表矩阵。如果我的输入是:
1 2 3
4 5 6
7 8 9
那么链表矩阵就是这样的:
1 -> 2 -> 3 -> NULL
| | |
v v v
4 -> 5 -> 6 -> NULL
| | |
v v v
7 -> 8 -> 9 -> NULL
| | |
v v v
NULL NULL NULL
我已尝试调试代码。我在col = col->down 中遇到分段错误错误。但我无法理解这个错误背后的原因。这是供您参考的代码。
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
struct node *down;
}matrix;
matrix *start = NULL;
void insert();
void arrToMatrix();
void arrDisplay();
void matrixDisplay();
int a[10][10];
int r,c;
int main()
{
int n;
printf("1:Insert elements 2:Convert Array to Linked Matrix 3:Display Array 4:Display Linked Matrix\n");
for(;;)
{
printf("Enter choice: ");
scanf("%d",&n);
switch(n)
{
case 1: insert();
break;
case 2: arrToMatrix();
break;
case 3: arrDisplay();
break;
case 4: matrixDisplay();
break;
default: printf("Wrong Input\n");
exit(0);
}
}
return 0;
}
void insert()
{
int i,j;
printf("Enter row: ");
scanf("%d",&r);
printf("\nEnter column: ");
scanf("%d",&c);
printf("Enter elements: \n");
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&a[i][j]);
}
void arrDisplay()
{
int i,j;
printf("Array elements: \n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
}
void arrToMatrix()
{
int i,j;
matrix *ptr, *col, *row;
ptr = malloc(sizeof(matrix));
ptr->data = a[0][0];
ptr->next = NULL;
ptr->down = NULL;
start = ptr;
col = start;
for(i=0;i<r;i++)
{
row = col;
for(j=0;j<c;j++)
{
ptr = malloc(sizeof(matrix));
ptr->data = a[i][j];
ptr->next = NULL;
ptr->down = NULL;
if(row == col)
row = ptr;
else
{
while(row->next!=NULL)
row = row->next;
row->next = ptr;
}
}
col = col->down;
}
}
void matrixDisplay()
{
matrix *row, *col, *ptr;
col = start;
while(col!=NULL)
{
row = col;
while(row!=NULL)
{
printf("%d ",row->data);
row = row->next;
}
printf("\n");
col = col->down;
}
}
【问题讨论】:
标签: c arrays matrix linked-list