我是C语言的新手,正在尝试创建字典的类似物,并遇到了打字问题。我的字典知道如何仅为 const char 创建键值,我想扩展程序,使其也可以使用其他数据类型的值,并尝试使用指向空的指针,但问题仍然存在,我有几个问题:
是否可以使函数将字典转换为不同类型的数据?
我该怎么做?
主要代码:
#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);
}
}
主要功能
#include "dict.c"
int main ()
{
dict_t *dict;
dict = newDict("key", "data\n");
printDict(dict);
return 0;
}
非常感谢。
答案 0 :(得分:0)
简短答案:您不能(但请看长答案)。
长答案:
您可以使用两种技巧,尽管它们并不完美。
第一个是空指针。
无效指针没有类型,因此可以用来指向任何指针的值。但是,指针不存储它指向的值的类型。这可能会引起问题,因为您必须使用类型强制转换来取消引用它,这需要您事先了解类型。您可以使用结构来存储类型和指针,然后使用if语句适当地取消引用它:
enum Type {
Int,
Str
//add more types
}
struct base {
enum Type type;
void *value;
}
第二个技巧是使用联合。与第一个非常相似,只是使用联合而不是void指针:
enum Type {
Int,
Str
//add more types here
}
struct base {
enum Type type;
union {
int i;
char s[20];
//add more types here
} values;
}
您将再次使用if语句来选择联合的正确字段。