【发布时间】:2014-02-25 15:16:32
【问题描述】:
我想创建一个程序:
- 创建一个二维数组,该数组由指向链表的指针组成,链表包含一个名为 result 的整数和一个 *next 指针
- 首先将数组的所有元素设置为 NULL
- 然后,对于数组的每个位置 (i,j),通过 scanf 读取一个名为 temp 的整数。如果 temp==-1 继续到下一个 {i,j},如果 temp!=-1,则放入 temp在结果中,创建一个 NULL 列表作为
array[i][j]的下一个列表,并且在给定 temp 的新值的同时做同样的工作来扩大array[i][j]的列表。
我想出了写这段代码:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct linked_list *list;
struct linked_list
{
int result;
list next;
};
int main()
{
int i,j;
scanf("%d %d",&i,&j);
int l,k;
list **array=malloc(i*sizeof(list));
for(l=0;l<j;l++)
array[l]=malloc(j*sizeof(list));
for(l=0;l<i;l++)
{
for(k=0;k<j;k++)
{
array[i][j]=NULL;
}
}
int temp;
list new;
list current;
for(l=0;l<i;l++)
for(k=0;k<j;k++)
{
scanf("%d",&temp);
while(temp!=-1)
{
if (array[l][k]==NULL)
{
new->result=temp;
new->next=NULL;
array[l][k]->next=new;
}
else
{
current->result=temp;
current->next=NULL;
new->next=current;
}
scanf("%d",&temp);
}
}
int cnt=0;
for(l=0;l<i;l++)
for(k=0;k<j;k++)
{
if (array[l][k]==NULL)
printf("array(%d)(%d) is empty!\n",l,k);
else
{
do
{
cnt++;
printf("element no.%d of array(%d)(%d) is: %d\n",cnt,l,k,array[l][k]->result);
array[l][k]=array[l][k]->next;
}while (array[l][k]!=NULL);
}
}
return 0;
}
这是为了做我之前描述的事情。但是,使用正确的内存分配不是很灵活,即使在 i=1,j=1 运行此代码时,我也会得到“分段错误”作为输出。如果有人可以帮助我了解我必须做什么才能正确分配所需的内存,我会非常高兴!
提前致谢!
【问题讨论】:
-
首先,
array[i][j]=NULL;显然是错误的 -
我需要用什么来代替它?
-
例如你可以用arrap[i][j]=-1替换它
标签: c arrays list pointers linked-list