C语言如何将数据类型字符串转为对应保留字供sizeof识别
问题解答
不存在直接让sizeof运算符识别字符串形式类型名的方法。
sizeof是C语言标准规定的编译期运算符,所有计算逻辑都在程序编译阶段完成:编译器必须在编译时就拿到明确的类型/表达式作为操作数,才能计算出对应占用的内存大小。等程序编译完成运行起来之后,C语言本身没有内置运行时类型信息,你数组里存的"char"、"unsigned int"本质就是普通的字节序列,和C语言的类型保留字没有任何关联,sizeof根本不可能在运行阶段解析这些字符串。
可行实现方案
方案1:手动维护类型-大小映射表(最推荐)
你可以提前把所有需要支持的类型和它对应的sizeof结果绑定成键值对,运行时遍历匹配字符串拿到对应大小即可,实现简单、零额外依赖、运行效率高。
参考实现代码:
#include <stdio.h> #include <string.h> #include <stddef.h> // 类型大小映射条目 typedef struct { const char* type_name; size_t type_size; } TypeSizeEntry; int main() { // 提前注册所有需要支持的类型,编译期就会计算好各类型的大小 TypeSizeEntry type_map[] = { {"char", sizeof(char)}, {"signed char", sizeof(signed char)}, {"unsigned char", sizeof(unsigned char)}, {"short", sizeof(short)}, {"unsigned short", sizeof(unsigned short)}, {"int", sizeof(int)}, {"unsigned int", sizeof(unsigned int)}, {"long", sizeof(long)}, {"unsigned long", sizeof(unsigned long)}, {"long long", sizeof(long long)}, {"unsigned long long", sizeof(unsigned long long)}, {"float", sizeof(float)}, {"double", sizeof(double)}, {"long double", sizeof(long double)}, {"void*", sizeof(void*)} // 有其他需要支持的类型直接往这里追加即可 }; // 你原来的类型名数组 const char* list_of_datatypes[] = {"char", "unsigned int", "double", "long long"}; int map_len = sizeof(type_map) / sizeof(type_map[0]); int list_len = sizeof(list_of_datatypes) / sizeof(list_of_datatypes[0]); for (int i = 0; i < list_len; i++) { size_t target_size = 0; for (int j = 0; j < map_len; j++) { if (strcmp(list_of_datatypes[i], type_map[j].type_name) == 0) { target_size = type_map[j].type_size; break; } } if (target_size) { // 注意:sizeof返回size_t类型,占位符要用%zu,不要用%lu避免跨平台打印出错 printf("%s 类型占用大小:%zu 字节\n", list_of_datatypes[i], target_size); } else { printf("未识别的类型:%s\n", list_of_datatypes[i]); } } return 0; }
这个方案的缺点是需要手动枚举所有用到的类型,无法自动覆盖所有合法的C类型,但对于绝大多数业务场景来说完全够用。
方案2:运行时编译/解释C代码(极不推荐)
如果你确实需要动态识别任意输入的C类型名,可以在程序里嵌入轻量C解释器,或者运行时调用系统C编译器把类型名拼成临时代码片段、编译后读取大小。但这个方案会引入非常大的依赖和性能开销,还可能带来安全风险,没有特殊需求不要使用。
内容的提问来源于stack exchange,提问作者mortonPI
相关产品推荐
相关产品推荐

