为什么我们不制作一个大小等于我的计算机内存的数组?

huangapple go评论65阅读模式
英文:

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 &lt;iostream&gt;
using namespace std;

int main int()
{
    size_t max_value = (size_t)-1;
    cout &lt;&lt; max_value &lt;&lt; endl;

    int *ptr = (int *)malloc(sizeof(int) * (max_value));
    for(size_t i = 0; i &lt; max_value;i++)
    {
        cout &lt;&lt; ptr[i] &lt;&lt; endl;
    }
    cout &lt;&lt; &quot;done&quot;&lt;&lt;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&lt;size_t&gt;::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&lt;size_t&gt;::max().

huangapple
  • 本文由 发表于 2023年2月6日 17:32:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75359510.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定