我想创建一个链接列表,它可以在运行时接受任何数据类型并显示列表。问题是不同数据类型的显示功能和内存管理更改。所以我不知道该怎么做。代码示例将不胜感激。
编辑:缩小问题范围。这是队列结构(使用链表)
struct node
{
void *data;
struct node *link;
};
struct queue
{
struct node *front;
struct node *rear;
};
现在添加新元素和显示的调用函数如下:
int main()
{
struct queue* q;
void *a;
char ch;
printf("do you want to add an element?(y/n)\n");
scanf("%c",&ch);
while(ch!=n)
{
printf("Enter the element\n");
scanf("%p",a);
enqueue(q,a);
display(q);
}
return 0;
}
以下是我的入队函数定义:
void enqueue(struct queue* queue,void* item)
{
if(queue->logical_length==queue->cnt_max)
{
printf("Queue is full\n");
return;
}
else
{
struct node*temp;
temp=(struct node*)malloc(sizeof(struct node));
temp->data=malloc(queue->data_size);
temp->link=NULL;
memcpy(temp->data,item,queue->data_size);
if(queue->front==NULL)
{
queue->rear=queue->front=temp;
queue->logical_length=queue->logical_length+1;
return;
}
queue->rear->link=temp;
queue->rear=temp;
queue->logical_length=queue->logical_length+1;
}
}
这里,问题是如果我甚至不知道数据类型,如何将内存分配给数据字段。因此,如果有某种方法可以找到运行时输入值的数据类型,那就更好了。
以下是我的显示功能:
void display(struct queue* queue)
{
struct node* temp;
if(queue->front==NULL)
{
printf("Queue is empty\n");
return;
}
else
{
temp=queue->front;
while(temp->link!=NULL)
{
printf("%p \t",*(void *)temp->data);
temp=temp->link;
}
printf("%p \t",*(void *)temp->data);
}
}
这里输出总是一些随机数。
答案 0 :(得分:0)
您可以通过两种方式存储数据。
insert
的函数将存储控制权移交给队列; extract函数将控制权返回给调用代码。这意味着队列不需要知道指向了多少数据。insert
函数数据块的大小以及存储位置(void enqueue(struct queue *queue, void *item, size_t length)
)。但是,这意味着您只能安全地复制(使用memmove()
或等效的)数据结构。许多结构都不能像那样复制(想想包含指针的结构)。对于第一种机制,display()
函数被改为apply()
函数,该函数被赋予函数指针:
void apply(struct queue *queue, void *data, void (*function)(const void *item, void *data));
遍历queue
,并使用队列中的当前项加上传递给apply
函数的数据调用该函数。此数据是指向使函数正常工作所需的任何上下文的指针。对于显示,它可能是FILE *
,或者它可能是更复杂的结构。无论哪种方式,函数(函数指针function
指向)都知道如何处理数据,因为它与数据类型相协调。