gpt4 book ai didi

c - 链表中具有字符数组的节点的内存分配

转载 作者:太空宇宙 更新时间:2023-11-04 08:20:54 26 4
gpt4 key购买 nike

OK,这是一个简单的c语言单链表程序

struct node
{
int id;
char name[20];
int sem;

struct node *link;
};

typedef struct node* Node;

Node getnode()
{
Node temp=(Node)(malloc(sizeof(Node)));
if(temp==NULL)
printf("\n Out of memory");

return temp;
}

Node ins_pos(Node first)
{
Node temp=getnode();
printf("\n Enter id ");
scanf("%d",&temp->id);
printf("\n Enter name ");
scanf("%s",temp->name);
printf("\n Enter semester ");
scanf("%d",&temp->sem);

if(first == NULL)
{
temp->link=NULL;
return temp;
}

else
{
int pos,i;
printf("\n Enter position: ");
scanf("%d",&pos);

if(pos == 1)
{
temp->link=first;
return temp;
}

else
{
Node prev=NULL,cur=first;
for(i=1; i<pos; i++)
{
if(cur==NULL)
break;

prev=cur;
cur=cur->link;


}

if(cur==NULL && i < pos)
printf("\n Position invalid");
else
{
prev->link=temp;
temp->link=cur;
}

return first;
}
}
}

Node del(Node first)
{
if(first==NULL)
printf("\n List is Empty ");
else
{
Node temp=first;
printf("\n ID: %d was deleted",temp->id);
first=first->link;
free(temp);
}
return first;
}

void disply(Node first)
{
if(first==NULL)
printf("\n List is empty");
else
{
Node cur=first;
while(cur!=NULL)
{
printf("\n ID : ");
printf("%d",cur->id);
printf("\n Name : ");
printf("%s",cur->name);
printf("\n Semester : ");
printf("%d",cur->sem);
printf("\n\n\n");

cur=cur->link;
}
}
}
int main()
{
Node first=NULL;
int opt;

do
{
printf("\n QUEUE MENU\n 1.Insert at position \n 2.delete front\n 3.display\n 4.Exit \n\n Enter your choice : ");
scanf("%d",&opt);

switch(opt)
{
case 1 :first = ins_pos(first);
break;

case 2 :first = del(first);
break;

case 3 :disply(first);
break;

}


}while(opt!=4);


return 0;
}

插入新节点时,代码块在 malloc 语句处崩溃。我怎么知道?好吧,它在询问“输入 ID”之前崩溃了。那么,我做错了什么吗?

这里的另一点是,它在节点中只有一个整数字段时工作正常,这里的问题可能是字符数组。

最佳答案

在这个函数中 Node getnode() -

Node temp=(Node)(malloc(sizeof(Node)));

使用上面的 malloc,您分配的内存等于 Node 的大小,它是 struct pointer 类型,但不够。因此,您会遇到段错误。

不是这样写的-

Node temp=malloc(sizeof(*temp));        //also there is no need of cast

这将分配与 temp 指向的类型大小相等的内存,即大小等于结构的大小。哪个合适。

关于c - 链表中具有字符数组的节点的内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33461344/

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