英文:
why we not make array of size max of my computer memory?
问题
#include <iostream>
using namespace std;
int main int()
{
size_t max_value = (size_t)-1;
cout << max_value << endl;
int *ptr = (int *)malloc(sizeof(int) * (max_value));
for(size_t i = 0; i < max_value;i++)
{
cout << ptr[i] << endl;
}
cout << "done"<<endl;
return 0;
}
int *ptr = (int *)malloc(sizeof(int) * (max_value));
这一行为什么代码被终止了?
你能解释一下这段代码发生了什么吗?
英文:
#nclude <iostream>
using namespace std;
int main int()
{
size_t max_value = (size_t)-1;
cout << max_value << endl;
int *ptr = (int *)malloc(sizeof(int) * (max_value));
for(size_t i = 0; i < max_value;i++)
{
cout << ptr[i] << endl;
}
cout << "done"<<endl;
return 0;
}
int *ptr = (int *)malloc(sizeof(int) * (max_value));
why does the code get killed on this line?
Can you explain what's happing in this code?
答案1
得分: 0
std::numeric_limits<size_t>::max()
是一个 size_t
可以表示的最大数字。以字节为单位,它是 18,446,744 兆字节。我将假设您的系统没有那么多内存。
将这个数字乘以 sizeof(int)
不会使这个数字变成四倍大(这是不可能的)。相反,内部的位模式向左移动了两位,从而将 std::numeric_limits<size_t>::max()
减小了3。
英文:
std::numeric_limits<size_t>::max()
is the largest number a size_t
can express. Measured in bytes, it is 18,446,744 terabytes. I am going to assume your system does not have that much memory.
Multiplying this number by sizeof(int)
does not make this number four times bigger (it is impossible). Instead, the bit pattern inside gets shifted to the left by two places, which has the net effect of subtracting 3 from std::numeric_limits<size_t>::max()
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论