【问题标题】:Conversions of different data types不同数据类型的转换
【发布时间】: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


【解决方案1】:

简答:你不能(但请看长回答)。

长答案:

您可以使用两种技巧,尽管它们并不完美。

第一个是空指针。

void 指针没有类型,因此可以用来指向任何指针的值。但是,指针不存储它指向的值的类型。这可能会导致问题,因为您必须使用类型转换来取消引用它,这需要您事先知道类型。您可以使用结构来存储类型和指针,然后使用 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 语句来选择联合的正确字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 2021-05-02
    相关资源
    最近更新 更多