Я пытаюсь создать единый связанный список в C, способный хранить данные другого типа. т.е. я хочу сохранить числа с плавающей точкой в списке, но также и структуры в том же списке. Моя основная проблема (насколько я знаю) - это memcpy, используемый в узле. c для копирования полученных данных пользователем в указатель в структуре TNode.
list.h
#include "node.h"
typedef struct {
TNode *h;
TNode *t;
int tamInfo;
} TList;
список. c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "list.h"
/*Function to store a TList reserving enough space dynamically*/
TList* newList(int tamInfo) {
TList *list = (TList*)malloc(sizeof(TList));
list->h = list->t = NULL;
list->tamInfo = tamInfo;
return list;
}
/*This function receives the type of list "Tlist* list",
and the information to store in it "void* info" (see main.c)*/
void addNode(TList* lis, void* info) {
TNode *p = createNode(lis,info);
if (lis->h == NULL) {
lis->h = p;
lis->t = p;
return;
}
else {
TNode* punt = lis->h;
while (punt->s != NULL) {
punt = punt->s;
}
punt->s = p;
}
}
node.h:
struct Node{
void *dato;
struct Node *s;
};
typedef struct Node TNode;
узел . c
#include <stdlib.h>
#include <string.h>
#include "nod.h"
/* This function receives "void* dato" which is a struct TList,
and "int tam" which depends on the main.c (it can be a float, int or even a string) */
TNode* createNode(void* dato, int tam) {
TNode *q = (TNode*)malloc(sizeof(TNode));
q->dato = malloc(sizeof(tam));
q->s = NULL;
/* q->dato = tam; If I do it this way, it works in some cases. But I want to make it work in all cases, i.e. when using strings */
memcpy((void*)q->dato, tam, sizeof(tam)); // I've tried using memcpy(q->dato, dato, sizeof(dato)); and other variations such as memcpy(q->dato, tam, sizeof(tam));
printf("q->dato = %lf\n", *(double*)q->dato); //First I'm using this to print it as a float value (I send a float number in the variable tam)
return q;
}
main. c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "list.h"
typedef struct {
char Name[20];
int age;
} TPersona;
}
int main()
{
TList *listN, *listP;
double x;
TPersona p, *q;
char r;
listN = newList(sizeof(double));
listP = newList(sizeof(TPersona));
do {
printf("Give me a real number: ");
scanf("%lf",&x);
if (x>=0) {
addNode(listN,&x);
}
} while (x>=0);
do {
printf("Name: ");
scanf("%s",p.Name);
printf("Age: ");
scanf("%d",&(p.age));
if (p.age>0)
addNode(listP,&p);
} while (p.age>0);