Nip*_*tra 1 c arrays types sizeof
是否可以使用for循环在C中获取所有基本数据类型的大小?例如,我们可以这样做吗?
#include <datatypes.h> /* or something else which defines get_data_types() */
#include <stdio.h>
int main() {
for (int x = 0; x < len(get_data_types()); x++) {
printf("Size of %s is %d", get_data_types()[x], sizeof(get_data_types()[x]));
}
}
Run Code Online (Sandbox Code Playgroud)
我可以通过替换for循环并为int,long等编写单独的语句来枚举所有数据类型.但是,我想知道是否有可能有一个for循环来做同样的事情?
基本上,我试图避免以下情况:
#include <stdio.h>
int main() {
printf("Size of int is %d", sizeof(int);
printf("Size of unsigned int is %d", sizeof(unsigned int);
printf("Size of long is %d", sizeof(long);
/* etc. */
return 0;
}
Run Code Online (Sandbox Code Playgroud)
数据类型的兴趣 - ,char,unsigned char,signed char,int,unsigned int,short,unsigned short,long,unsigned long,,floatdoublelong double
澄清:我不一定需要一组混合类型,但能够枚举类型以便可以轻松访问大小.
不,这是不可能的.没有办法自动列出C中的所有类型.您必须手动为每种类型执行此操作.
但是,如果您经常使用这些信息,您可以提前准备一份清单.有一些方法可以做到这一点.这是一:
#include <stdio.h>
#include <string.h>
typedef struct {
char name[20];
int size;
} type;
int main()
{
type types[3] = { {"int", sizeof (int) },
{"char", sizeof (char) },
{"double", sizeof (double) } };
for (int x = 0; x<sizeof(types)/sizeof(types[0]); x++)
printf("Size of %s is %d\n", types[x].name, types[x].size);
}
Run Code Online (Sandbox Code Playgroud)
(代码简化为Paul Ogilvie在下面的答案的灵感.)
在对这个答案的评论中你问:我们可以创建一个如下所示的数组:types_array = {"int","char","double","long"}并且在迭代时得到相应的大小?我的意思是说使用一些函数f,我们可以将类型[j] .size分配给sizeof(f(types_array [j]))
简而言之,没有.这是因为C是强类型编译语言.在像Python和PHP这样的语言中,你可以做各种各样的花哨的东西,但在C号.不是没有诡计.f示例中的函数必须具有指定的返回类型,这是sizeof将作为参数获取的类型.
解决它的一种方法是编写自定义sizeof:
int mysizeof(char * s) {
if(strcmp(s, "char") == 0)
return sizeof(char);
if(strcmp(s, "int") == 0)
return sizeof(int);
}
Run Code Online (Sandbox Code Playgroud)
如果此列表很长,您可以使用宏:
#define MYSIZEOF(x) if(strcmp(s, #x) == 0) return sizeof(x)
int mysizeof(char * s) {
MYSIZEOF(int);
MYSIZEOF(char);
MYSIZEOF(double);
}
Run Code Online (Sandbox Code Playgroud)