C中为浮点数分配的内存大小
#include <stdio.h>
#define max_size 100
float array[max_size];
int n,counter;
int main(){
printf("Enter the size of the array...n");
scanf("%d",&n);
for (counter=0; counter<n; counter++){
printf("%pt",&array[counter]);
}
printf("nn");
return 0;
}
我只是在试验这个 C 程序,我试图验证浮点数的大小是否为 8 个字节。但是在使用数组中的 5 个元素运行此代码时,我得到这些元素的地址如下:
Enter the size of the array...
5
0x555555755040 0x555555755044 0x555555755048 0x55555575504c 0x555555755050
正如你看到的第一个浮点数,我的系统已经分配了内存空间 ...40,41,42,43 如果我没记错的话,这是 4 位的空间。但是 float 数据类型应该有 8 个字节的空间。我认为该程序应该为 2 个字节的空间分配内存空间 ...40,41,...4F。所以
...40-...4F //for first 2 bytes
...50-...5F //for second 2 bytes
...60-...6F //for third 2 bytes
...70-...7F //for last 2 bytes
所以第二个地址将从 ...80 开始。但这不是我得到的结果。在这个过程中我缺少什么?感谢您的帮助 !!
回答
C 标准没有说明 的存储大小,float并且它已被故意忽略给实现者。
也许在您的系统和编译器上,大小为 4。您可以使用sizeof(float). 另请参阅此讨论。
- This is the correct answer. The size of the different types vary from system to system.