我想要打印
"(类型)的大小是(类型的大小)字节"
例如
"int的大小是4Byte"
由下面的代码.但是它说
"int的大小是8Byte"
我认为这段代码显示了string(int)的大小,但是int类型.我怎么解决这个问题?
码
#include <stdio.h>
char *variabletype[] = {"char", "unsigned char", "signed char", "int", "unsigned int", "short", "unsigned short", "long", "unsigned long", "long long", "unsigned long long"};
int main() {
for (int i = 0; i < 11;++i) {
printf("Size of %s is %u\n",variabletype[i], (unsigned int)(sizeof(variabletype[i])));
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
返回
Size of char is 8Byte
Size of unsigned char is 8Byte
Size of signed char is 8Byte
Size of int is 8Byte
Size of unsigned int is 8Byte
Size of short is 8Byte
Size of unsigned short is 8Byte
Size of long is 8Byte
Size of unsigned long is 8Byte
Size of long long is 8Byte
Size of unsigned long long is 8Byte
Run Code Online (Sandbox Code Playgroud)
sizeof是在编译时计算的运算符.它返回一个编译时常量(VLA除外).在您的代码中,您始终打印(在您和我的计算机上恰好是8).请记住,即使数组衰减为指针,数组也不会与指针相同.sizeof(char*)
你要:
printf ("sizeof int is %zu\n", sizeof(int));
printf ("sizeof long is %zu\n", sizeof(long));
Run Code Online (Sandbox Code Playgroud)
#define PRINTSIZE(Type) printf("sizeof " #Type " is %zu\n", sizeof(Type))
PRINTSIZE(int);
PRINTSIZE(long);
Run Code Online (Sandbox Code Playgroud)
C语言将翻译时间和运行时间分开.实际上,您正在使用编译器(有时甚至是交叉编译器).标准C中没有eval运算符.
在许多操作系统上,您可以运行另一个编译过程(可能使用system或popen(3)),但是如何运行编译器是系统特定的(在Linux上,您经常使用gcc;在Windows上,它可能是其他的) .
所以原则上你可以在Linux上编写一个生成临时C文件的程序,然后对某些计算字符串使用system(3)两次:一次运行编译,另一次运行生成的可执行文件.但这很复杂(而且不便携),所以不值得你花时间.
请注意,在C(和C++)中,类型,语句,表达式,变量名称等只有编译器知道,并且在运行时不存在(运行时只有内存位置).在C11标准(读n1570)提到翻译单元.
也许你梦想有一些同性恋编程语言.然后不要使用C,而是使用Common Lisp等语言.尝试SBCL,Common Lisp实现正在将每个REPL交互转换(即编译)您的表达式到机器代码中.
| 归档时间: |
|
| 查看次数: |
170 次 |
| 最近记录: |