gpt4 book ai didi

c - 在 C 中打印所有列表元素

转载 作者:行者123 更新时间:2023-11-30 16:01:06 26 4
gpt4 key购买 nike

我在c中为List构建了这个接口(interface),我插入到结构体数组的列表指针中,现在我想打印结构体的所有字段,我该怎么做?

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

typedef struct element {
void *item;
struct element *next;
} Element;

typedef Element* position;
typedef Element* List;

typedef struct strc
{
int row,col,value;
} Strc;

List initList()
{
Element *ls=malloc(sizeof(Element));
if(ls)
ls->next=NULL;
else
ls=NULL;
return ls;
}

position insertToList(position p, void *item)
{
position newp=malloc(sizeof(Element));
if(newp)
{
newp->next=p->next;
p->next=newp;
newp->item=item;
//p=p->next;
}
else newp=NULL;
return newp;
}

void *retriveFromList(position p) { return p->item; }

position Next(position p) { return (position)p->next; }

int isEmpty(List ls) { return ls->next==NULL; }

void freeList(List ls)
{
position pos=ls->next;
while(ls->next!=NULL)
{
pos=ls->next;
ls->next=pos->next;
free(pos);
}
}
void puts(List *ls)
{
Position p=*ls;
Strc *tmp;
int i;
for(i=0;i<10;i++)
{
tmp=(Strc *)malloc(sizeof(strc));
tmp->row=i;
tmp->col=i+1;
tmp->value=i+2;
p=insertToList(p,tmp);
}
}
void print_list(List ls)
{
position p=ls->next;
while(p!=NULL)
{
printf("%3d\n",*((int*) retriveFromList(p)));
p=Next(p);
}
}

void main()
{
List ls=initList();
puts(&ls);
print(ls);
}

最佳答案

所以,我的 C 并不伟大

但是,当你运行这个程序时,似乎有大量的小打字错误会吞噬你。最大的问题之一是 puts() 已经在 stdio.h 中定义。

首先,这个东西不能为我编译,所以解决所有编译器错误让我走得很远。您的 puts 函数也缺少右括号。我将其重命名为 putv() 并将其更改为以下内容。

void putv(List *ls)
{
position p=*ls;
Strc *tmp;
int i;
for(i=0;i<10;i++)
{
if(tmp=(Strc *)malloc(sizeof(Strc)))
{
tmp->row=i;
tmp->col=i+1;
tmp->value=i+2;
p=insertToList(p,tmp);
}
}
}

第二个问题是您的 main 函数没有调用 print_list(),而是调用普通的 print()

void main()
{
List ls=initList();
putv(&ls);
print_list(ls);
}

这并不能解决您的所有问题

主要是因为我认为它没有打印出您想要的内容,但我会留下一些内容让您弄清楚。

关于c - 在 C 中打印所有列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7131447/

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