c - 如何将 void * 转换为 int 而不会丢失信息(在 c 中)?
问题描述
如果 void* 包含可变数量的信息,那么简单地将其存储在整数中可能会丢失信息吗?信息不应该存储在几个整数(又名 int*)中吗?
前任:
int func(void* info){
int num = (int)info;
return num;
}
如果 info = Absdfsdfskewlrew.... ,难道 num 不能正确保存这些信息吗?
解决方案
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
推荐阅读
- google-drive-api - 如何将谷歌驱动器文件夹连接到谷歌colab
- android - Webrtc Android 视频通话录音
- c - K&R c编程书3.7修剪功能示例
- c++ - C++ std::scoped_lock 允许嵌套
- java - 在过滤条件之后迭代流时如何获取上一个对象
- laravel - Swift_TransportException 进程无法启动[系统找不到指定的路径。]
- python - 无法理解 joblib.load
- verilog - 如何将 case inside 语句识别为完全涵盖的 case
- user-accounts - OpenEDX API:如何重置密码?
- c# - 将子控件上按钮的点击事件传递给父控件