【发布时间】:2017-01-23 08:08:47
【问题描述】:
下面是通用链表的代码。代码不工作。无法弄清楚出了什么问题。没有编译错误,但没有输出。
#include<iostream>
#include<stdlib.h>
using namespace std;
struct Node{
void* data;
Node* next;
};
void Insert(Node** head,void* k,size_t data_size){
Node* temp=(Node*)malloc(sizeof(Node));
temp->data=malloc(data_size);
temp->next=*head;
for(int i=0;i<data_size;i++){
*((char*)(temp->data) + i) = *((char*)(k )+ i);
}
*head=temp;
}
void PrintList(Node* head,void (*fptr)(void*)){
Node* temp=head;
while(temp!=NULL){
(*fptr)(temp->data);
temp=temp->next;
}
}
void PrintInteger(void* k){
printf("%d",*(int*)(k));
}
void PrintFloat(void* k){
printf("%f",*(float*)k);
}
int main(){
int a[]={4,1,9,5};
float b[]={1.3,7.6,2.5,4.7};
Node*head=NULL;
unsigned int_size=sizeof(int);
unsigned float_size=sizeof(float);
for(int i=3;i>=0;i++){
Insert(&head,&a[i],int_size);
}
PrintList(head,PrintInteger);
cout<<endl;
Node* head2=NULL;
for(int i=3;i>=0;i++){
Insert(&head2,&b[i],float_size);
}
PrintList(head2,PrintFloat);
}
【问题讨论】:
-
看起来不像
PrintList打印任何东西... -
Insert中的循环可以替换为对memcpy()的调用。 -
@evsheino 它调用
fptr回调,打印元素。 -
你试过用调试器单步调试代码吗?
-
你为什么要写 C 风格的代码?帮自己一个忙,买一本关于现代 C++ 的书
标签: c++ generics linked-list