gpt4 book ai didi

c - 尝试取消引用指针 : C 时出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 00:24:07 25 4
gpt4 key购买 nike

我正在尝试实现循环队列功能。我是一名 C++ 编码员,令我惊讶的是,在 C 中,struct 不能有成员函数。不管怎样,这是我的实现:-

#include <stdio.h>
#include <stdlib.h>



struct node
{
int nvalue;
struct node *next;
};

struct CLlist
{
struct node* head;
struct node* tail;
int size;
};

void insert(struct CLlist *l,int num)
{
struct node *n=malloc(sizeof(struct node));
n->nvalue=num;
n->next=NULL;

if((l->head==l->tail)==NULL)
{
l->head=l->tail=n;
}
else if(l->head==l->tail && l->head!=NULL)
{
l->head->next=n;
l->tail=n;
l->tail->next=l->head;
}
else
{
l->tail->next=n;
l->tail=n;
l->tail->next=l->head;
}
l->size++;
}

void print(struct CLlist *l)
{
int idno=1;
printf("printing the linked list with size as %d\n",l->size);
struct node *cptr;
for(cptr=(l->head);cptr!=(l->tail);cptr=cptr->next)
{
printf("The idno is %d and the number is %d\n",idno,cptr->nvalue);
idno++;
}
//this is to print the last node in circular list : the tail node
idno++;
cptr=cptr->next;
printf("The idno is %d and the number is %d\n",idno,cptr->nvalue);
}


int main()
{
struct CLlist a;
struct CLlist *l;
l=&a;

insert(l,2);
insert(l,5);
insert(l,7);
insert(l,10);
insert(l,12);
print(l);


return 0;
}

我在行中遇到段错误

printf("idno为%d,编号为%d\n",idno,cptr->nvalue);

为什么会出现这个错误?我想我没有正确地按值传递 l by pointer (按值传递指针)。有人可以帮我指出我哪里出错了吗?

谢谢

最佳答案

您永远不会在 main 函数中初始化变量 a,因此它的内容是不确定的,使用该结构的成员将导致未定义的行为

关于c - 尝试取消引用指针 : C 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36819020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com