Home  >  Q&A  >  body text

c++ - 运行窗口显示大小(问题比较low)

#include<iostream>
using namespace std;

int main(){
    int array[5000000];

    for(int i = 0; i < 5000000; i++)
    {
        array[i] = i;
        cout << array[i] << " ";
    }
    return 0;

}

用的是Dev c++
要显示从1到5000000
运行窗口什么都不显示,并且弹出窗口已停止工作的提示窗口
但是如果显示1到500,是可以的
是不是有显示限制?
如果是显示限制问题,有没有哪些工具是没有限制的?

巴扎黑巴扎黑2765 days ago636

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 12:02:41

    It exceeds the maximum length of array initialization. Such a large array is dynamically allocated using new

    Supplement:
    Because during initialization, memory allocation is on the stack, and the stack space is generally small. Therefore, if the initialized array is slightly larger, stack overflow will occur. However, during dynamic allocation, memory is allocated on the heap. The heap space is generally relatively large, so the needs of the subject can be met.

    To sum up, change the code to the following and it will run normally:

    #include <iostream>
    using namespace std;
    
    int main(){
        // int array[5000000];
        int* array = new int[5000000];
    
        for(int i = 0; i < 5000000; i++)
        {
            array[i] = i;
            cout << array[i] << " ";
        }
        cout << "end" << endl;
        delete[] array; // 不要忘记清理动态分配内存
        return 0;
    
    }
    

    Reference link:
    http://stackoverflow.com/questions/1847789/segmentation-fault-on-large...

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 12:02:41

    C/C++ is divided into local variables and global variables.
    Global variables are declared outside the int main() main function.
    Just put array[5000000]; in the main function and it will be OK

    reply
    0
  • Cancelreply