I am new to C and trying to create an analogue of the dictionary, and ran into a typing problem. My dictionary knows how to create a key-value only for const char, I wanted to expand the program so that it could also use values of other data types, tried to use a pointer to void, but the problem remained and I had a few questions:
Is it possible to make so that the function has converted the dictionary different types of data?
How can I do this?
main code:
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#define MAXSIZE 5000
struct base
{
uint8_t *up;
uint8_t size;
};
typedef struct
{
struct base key[MAXSIZE];
struct base data[MAXSIZE];
uint8_t index;
} dict_t;
static dict_t *init (uint8_t s_key, uint8_t s_data)
{
dict_t *dict;
dict = (dict_t *) malloc(sizeof(dict_t));
dict -> key -> up = (uint8_t *) malloc(s_key);
dict -> data -> up = (uint8_t *) malloc(s_data);
dict -> key -> size = s_key;
dict -> data -> size = s_data;
dict -> index = 1;
return dict;
}
dict_t *newDict (const char *key, const char *data)
{
dict_t *dict;
uint8_t s_key;
uint8_t s_data;
s_key = strlen(key);
s_data = strlen(data);
dict = init(s_key, s_data);
memcpy(dict -> key, key, s_key);
memcpy(dict -> data, data, s_data);
return dict;
}
void printDict (dict_t *dict)
{
for (int i = 0; i < dict -> index; i++)
{
fwrite(dict -> key, sizeof(uint8_t), dict -> key -> size, stdout);
fwrite(": ", sizeof(char), 2, stdout);
fwrite(dict -> data, sizeof(uint8_t), dict -> data -> size, stdout);
}
}
main function
#include "dict.c"
int main ()
{
dict_t *dict;
dict = newDict("key", "data\n");
printDict(dict);
return 0;
}
Thanks a lot.