我的目标是创建一个大于 4 字节的整数类型,如果我使用 long,则为 8 字节。我尝试使用 malloc 尝试在内存中提供更多字节以获取更大的整数,但在第 31 次迭代时它仍然崩溃(给出负数)。这是我的代码:
int main()
{
int x = 31; //(normally an int can do up to 30 without going negative so this is my test number)
int i;
int *bigNum = NULL;
bigNum = malloc((sizeof(int)*2));
*bigNum = 1;
for (i=0; i<x; i++) {
*bigNum = *bigNum * 2;
printf("%d \n", *bigNum);
}
free(bigNum);
}
输出:
2
4
...
..
...
1073741824
-2147483648
最佳答案
尽管您为整数分配了更多内存,但系统的其他部分不知道这一点,包括:
编译器不知道这一点;
CPU 芯片不知道这一点。
printf 不知道这一点。
所以所有的计算都是使用原生 int 大小进行的。
请注意,您无法告诉 CPU 芯片您使用了更大的整数;这是芯片的物理/设计限制。
关于c - Malloc() 为整数创建新的大小以用于数学 - 需要指导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41825199/