首页 > 解决方案 > 如何将 void * 转换为 int 而不会丢失信息(在 c 中)?

问题描述

如果 void* 包含可变数量的信息,那么简单地将其存储在整数中可能会丢失信息吗?信息不应该存储在几个整数(又名 int*)中吗?

前任:

int func(void* info){
int num = (int)info;
return num;
}

如果 info = Absdfsdfskewlrew.... ,难道 num 不能正确保存这些信息吗?

标签: ctype-conversion

解决方案


void*有时用于将指向“任何类型”值的指针传递给函数。

您还需要另一个参数来描述 void* 实际指向的内容,以便您可以将其转换为正确的指针类型。

以下示例说明了该概念:

#include <stdio.h>

typedef enum {
    what_int,
    what_float,
    what_string
} what_t;

void print_it(what_t what, void *value)
{
    switch (what) {
        case what_int:
            printf("It is an int: %d\n", * (int*) value);
            break;
        case what_float:
            printf("It is a float: %f\n", * (float*) value);
            break;
        case what_string:
            printf("It is a string: %s\n", (char*) value);
            break;
        default:
            printf("I don't understand what it is\n");
    }
}

int main()
{
    int i = 5;
    print_it(what_int, &i);

    float f = 3.1415;
    print_it(what_float, &f);

    char *s = "Hello world";
    print_it(what_string, s);

    return 0;
}

这个程序的输出是:

It is an int: 5
It is a float: 3.141500
It is a string: Hello world

推荐阅读