【问题标题】:Pointers in C and its interpretation as an arrayC中的指针及其作为数组的解释
【发布时间】: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) 对应的链接列表,即应该打印值 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);
}

是我的打印功能造成了错误,还是错误出现在其他地方?

【问题讨论】:

  • “但它反映了错误”是什么意思?有些东西不正常,你得到一个编译器错误......什么?
  • 为什么要为currenttemp 分配内存?我觉得您应该将数据直接存储在您为adjlist 分配的内存中。并且请不要从calloc() 转换返回值。
  • @CareyGregory :显示的错误是“左值需要作为赋值的左操作数”
  • @FilipeGonçalves :简而言之,我正在使用所有这些变量将节点动态添加到链表中。 calloc() 的类型转换返回值是多余的还是错误的?

标签: c pointers


【解决方案1】:

(adjlist+n-2) 是一个常量表达式。您不能在赋值语句的左侧使用它。我想你的意图是*(adjlist+n-2)

【讨论】:

  • 不,我仍然打算将地址分配给adjlist 位置的倒数第二个指针位置,即(adjlist+n-2)
  • 我的建议完全可以完成您认为可以解决您自己问题的事情;即adjlist[n-2]=*temp;。那么,我不明白您要完成的工作是什么?
  • 现在我不明白你的问题是什么。
【解决方案2】:

Copying structure in C with assignment instead of memcpy()

另一方面,您需要在第二次分配内存之前释放 temp,否则您将泄漏内存。

【讨论】:

    猜你喜欢
    • 2013-04-17
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多