【发布时间】:2020-05-08 20:32:46
【问题描述】:
我是 C 的新手,并试图创建字典的类似物,但遇到了打字问题。我的字典知道如何为 const char 创建一个 key-value,我想扩展程序以便它也可以使用其他数据类型的值,尝试使用指向无效的指针,但问题仍然存在,我有几个问题:
是否可以让函数将字典转换成不同类型的数据?
我该怎么做?
主要代码:
#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;
}
非常感谢。
【问题讨论】:
-
此链接不会立即回答您的问题(我不建议将其作为副本)。但是,您可能很快就会考虑使用 void 指针,并且可能会欣赏那里描述的概念:stackoverflow.com/questions/58280538/…(是的,这是我的另一个答案。整个问题和所有答案可能对您有所帮助。)
-
@Yunnosch 谢谢,我会看到
-
嗨 Gari,代码无法编译。我认为您需要在 dict 类型中的
base前面加上关键字struct。您也可以使用strlen()标准 clib 函数而不是自己滚动 (sizeVal()) -
@Jimbo 感谢已经修复。
-
@Gari - 你能发布编译代码吗?塔。
标签: c