c - C 中的指针及其对数组的解释

标签 c pointers

我正在尝试在邻接列表表示中保存图形,因此,我为此目的使用指针。编写整个代码片段是没有成果的,因此我正在编写该部分的代码片段,但我无法实现。

为了澄清起见,我使用 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) 对应的链表即应该打印值 1020。但只有第一个值(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/

相关文章:

c++ - 复制构造函数中的指针

C++ 成对合并列表元素

多个文件错误 : dereferencing pointer to incomplete type 中的 c 结构

c++ - 是否可以在不显式迭代每个元素的情况下深度复制指针容器?

将 uint32 变量转换为位域 - 未定义的行为?

c - 运行冒泡排序后出现运行时错误

c - 嵌套循环:inner loop is skipped once when executed

c - 快速 'C' 库可透明地管理非常大的文件

c - 如何从冒号分隔的文件中扫描整数值

c - 为什么 GDB 在行之间不可预测地跳转并将变量打印为 "<value optimized out>"?