c - 使用包含 union 和类型成员的结构

标签 c printf libvirt

我正在尝试调试我正在编写的使用 C 语言的 libvirt 库的程序。

在程序的一部分中,我返回了以下结构:

struct virTypedParameter {
    char field[VIR_TYPED_PARAM_FIELD_LENGTH];
    int type;
    union {
        int i;
        unsigned int ui;
        long long int l;
        unsigned long long int ul;
        double d;
        char b;
        char *s;
    } value;
}

所以我有一个键、值和值类型。我希望能够通过将它们传递给函数来打印它们。

除了将类型放入 switch 语句并重定向到正确的 printf 语句之外,还有更简单的方法吗?我已经这样做了,它导致编译时弹出大量警告:

void printVirTypedParameter(virTypedParameter* param) {
    printf("Param type: %d\n", param->type);
    switch(param->type) {
        case 1: //int
            printf("%s : %d\n", param->field, param->value);
            break;
        case 2: //int unsigned
            printf("%s : %u\n", param->field, param->value);
            break;
        case 3: //long long int
            printf("%s : %ld\n", param->field, param->value);
            break;
        case 4: //long long unsinged
            printf("%s : %llu\n", param->field, param->value);
            break;
        case 5: //double
            printf("%s : %f", param->field, param->value);
            break;
        case 6: //boolean (character)
            printf("%s : %c", param->field, param->value);
            break;
        case 7: //string
            printf("%s : %s", param->field, param->value);
            break;
        case 8: //param last
            printf("END_PARAMS");
}

最佳答案

开关就是做到这一点的方法。但是您应该使用适合您阅读的类型的 union 成员,即您应该使用 param->value.i如果你知道类型是 int 。这应该可以避免任何警告。

例如:

switch(param->type) {
        case 1: //int
            printf("%s : %d\n", param->field, param->value.i);
            break;
        // ...
}

关于c - 使用包含 union 和类型成员的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46040737/

相关文章:

C:在输入光标后插入要显示的符号

c - 将项目从 64 位移植到 32 位时 : float changed to long double gives error for %f

java - 从 libvirt relaxng 模式生成 java 类的最佳方法是什么?

c - 结构体指针数组

assembly - NASM x86_64 printf 第 7 个参数

python - 将 mmap 指针作为 mmap 对象从 C 传递给 python

google-chrome-extension - 为什么dart.io之类的只能在命令行应用中使用?

console - 如何从另一台机器的命令行访问 VM 控制台

c - 在 C 中格式化非常大的数字

char总是使用flex改变