【发布时间】:2014-10-03 20:26:12
【问题描述】:
我正在尝试将图形保存在邻接表表示中,因此,我为此目的使用了指针。写整个代码sn-p是没有成果的,所以我写了那部分的sn-p代码,我没有实现。
只是为了澄清,我使用current以便能够在末尾附加一个节点,我不需要遍历整个列表。
我不确定这种分配指针的方式是否正确。任何微妙的暗示都会有很大的帮助。 非常感谢!!
int n;
struct node{
int i;
struct node * next;
};
int main(){
printf("Enter nodes");
scanf("%d",&n);
struct node *adjlist=(struct node*)calloc(n,sizeof(struct node));
struct node *current=(struct node*)calloc(n,sizeof(struct node));
struct node *temp=(struct node*)calloc(1,sizeof(struct node));
temp->i=10;
temp->next=0;
/* PROBLEM IS HERE
What I want to do is :
(adjlist+n-2)=temp;
But it reflects the following error :
lvalue required as left operand of assignment
Hence, using the BELOW statement.*/
adjlist[n-2]=*temp;
current[n-2]=*temp;
temp=(struct node*)calloc(1,sizeof(struct node));
temp->i=20;
temp->next=0;
/* The same I want to implement here as well.*/
current[n-2].next=temp;
current[n-2]=*temp;
return 0;
}
更新:
我正在尝试打印与地址 (adjlist+n-2) 对应的链接列表,即应该打印值 10 和 20。但只有第一个值 (10) 被打印出来。我正在使用的打印功能是:
void printlist(struct node * adjlist){
struct node *list=adjlist+n-2;
while((*list).next!=NULL){
printf ("\t%d",list->i);
list=list->next;}
printf ("\t%d",list->i);
}
是我的打印功能造成了错误,还是错误出现在其他地方?
【问题讨论】:
-
“但它反映了错误”是什么意思?有些东西不正常,你得到一个编译器错误......什么?
-
为什么要为
current和temp分配内存?我觉得您应该将数据直接存储在您为adjlist分配的内存中。并且请不要从calloc()转换返回值。 -
@CareyGregory :显示的错误是“左值需要作为赋值的左操作数”
-
@FilipeGonçalves :简而言之,我正在使用所有这些变量将节点动态添加到链表中。 calloc() 的类型转换返回值是多余的还是错误的?
-
@Gaurav 见stackoverflow.com/questions/605845/…