我正在尝试在邻接列表表示中保存图形,因此,我为此目的使用指针。编写整个代码片段是没有成果的,因此我正在编写该部分的代码片段,但我无法实现。
为了澄清起见,我使用 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);
}
是我的打印函数造成了错误,还是错误出现在其他地方?
最佳答案
(adjlist+n-2)
是一个常量表达式。不能在赋值语句的左侧使用它。我认为您的意图是 *(adjlist+n-2)
。
关于c - C 中的指针及其对数组的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25235993/