c - 如何类型转换 void 指针?

标签 c casting type-conversion

我目前正在解决一个问题,我必须将 void 指针转换为有符号的 char,short,long,long long。 (这些看起来很简单,我可以创建一个 tmp,然后转换 void。)

令我困惑的是: 将 void 指针转换为: 有符号十进制、无符号八进制、无符号十进制、无符号十六进制、%f 转换 其中,“double arg 被四舍五入并覆盖为十进制表示法。

对于大多数这些转换,我只会使用 atoi 和正确的基数?

我将使用可变参数,并且知道该值实际上是什么,但我的计划是将所有内容类型转换为 void 指针,然后根据格式进行转换。转换是我不清楚的。为了清楚起见:我将 va_arg 转换为 void 指针,并将其存储在结构中。然后根据格式,我将每个空指针转换为正确的数据类型。我只是想弄清楚如何对上面列出的数据类型进行每次转换

感谢您提供的所有帮助。

void    ft_conversion_length_di(t_main *node)
{
    if (node->length == 'H')
        node->arg = (signed char)node->arg;
    if (node->length == 'h')
        node->arg = (short)node->arg;
    if (node->length == 'l')
        node->arg = (long)node->arg;
    if (node->length == 'E')
        node->arg = (long long)node->arg;
}

最佳答案

如果您从已知类型的可变参数函数中读取值,则 void * 不是您想要的。您可以从 void * 转换为另一种指针类型,但不能转换为“值”类型。

您想要的是一个可以保存您期望的任何类型的 union ,以及包含该 union 和类型指示符的结构。

例如

enum value_type {
    VAL_CHAR,
    VAL_SHORT,
    VAL_LONG,
    VAL_LONGLONG,
    VAL_FLOAT,
    VAL_DOUBLE
};

union val {
   char c;
   short s;
   long l;
   long long ll;
   float f;
   double d;
};

struct value {
    enum value_type type;
    union val v;
};


void myfunc(const char *format, ...)
{
    va_list ap;

    va_start(ap, format);
    while (/* has more values */) {
        struct value s;
        if (/* is char */) {
            s.type = VAL_CHAR;
            s.v.c = va_arg(ap, char);
        } else if (/* is short */) {
            s.type = VAL_SHORT;
            s.v.s = va_arg(ap, short);
        } else if (/* is long */) {
            s.type = VAL_LONG;
            s.v.l = va_arg(ap, long);
        } else if (/* is long long */) {
            s.type = VAL_LONGLONG;
            s.v.ll = va_arg(ap, long long);
        } else if (/* is float */) {
            s.type = VAL_FLOAT;
            s.v.l = va_arg(ap, float);
        } else if (/* is double */) {
            s.type = VAL_DOUBLE;
            s.v.l = va_arg(ap, double);
        }
        /* do something with s */
    }
    va_end(ap);
}

关于c - 如何类型转换 void 指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56874916/

相关文章:

c - 在 Windows 10 上使用 DrawThemeBackground 绘制的部分不正确

java优化挑剔: is it faster to cast something and let it throw exception than calling instanceof to check before cast?

在 C 中将 int 转换为 char 数组

c++ - 整数和 float 转换

c - 以下表达式中发生了什么转换?

excel - 将 9 位 CUSIP 代码转换为 ISIN 代码

php - php-src 中的 “zend_execute” 函数在哪里?

c - EXIT_FAILURE 与退出(1)?

c - 在 Delphi 中调用 C++ DLL 的问题

C# 自动转换接口(interface)方法