繁体   English   中英

尝试引用指针时出现分段错误:C

[英]segmentation fault when trying to deference pointer : C

我试图实现循环队列功能。 我是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 按值传递指针)。 有人可以帮助我指出我要去哪里哪里吗?

谢谢

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

您的代码有两个问题,第一个更严重。

您的第一个问题是未将CLlist结构的headtail成员初始化为NULL ,这可以(不确定)阻止任何实际数据存储在结构中。 可以通过在第一次insert调用之前在main添加以下两行来解决此问题:

l->head = NULL;
l->tail = NULL;

您的第二个问题是在此行中:

if((l->head==l->tail)==NULL)

看起来这是将l->headl->tailNULL进行了比较,它实际上是在将l->headl->tail进行了比较,然后将该布尔结果与NULL进行了比较,即有效为0 该行应更改为:

if((l->head == NULL) && (l->tail == NULL))

这将分别测试headtail指针,并且仅在它们均为NULL时才采用该分支。

你有一个指针

struct node *cptr;
// You're probably trying to access an unassigned pointer head in the next step
for(cptr=(l->head);cptr!=(l->tail);cptr=cptr->next)

根据标准,没有要求

a->heada->tail初始化为NULL

当你做了

struct CLlist a;

标准ISO / IEC 9899:201x第6.7.9-> 10条规定

如果未自动初始化具有自动存储期限的对象,则其值不确定。

实际上,您是:

struct CLlist a;
// missing something here.
struct CLlist *l;
l=&a;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM