【问题标题】:A strange error occur about allocate array and rand()关于 allocate array 和 rand() 出现一个奇怪的错误
【发布时间】:2014-09-27 09:21:59
【问题描述】:

我想用 rand() 函数填充大数组,当我通过 int h_in[N] 定义我的数组时,程序在 vs 2010 中崩溃,我令人惊讶的是,当我将它复制到在线编译器 ideone a link 时,一切正常。最后我在 VS 2010 中通过 h_in = (int *)malloc(N * sizeof(int)) 定义了数组,该程序有效。我无法弄清楚,希望有人指出我的错误。

#include <stdio.h>
#include <stdlib.h>

const int N = 1024 * 1024;


int main()
{

    //int *h_in = (int *)malloc(N * sizeof(int));
    int h_in[N];
    float sum = 0.0f;
    srand(1);

    for(unsigned int i = 0; i < N; i++) {
        h_in[i] = (rand() & 0xFF);
    }
    return 0;
}

【问题讨论】:

    标签: arrays exception random


    【解决方案1】:
    int h_in[N]; 
    

    在堆栈上分配。

    int * h_in = malloc(N * sizeof(int));
    

    在堆上分配。 [顺便说一句:不要转换malloc()的结果]

    默认堆栈大小为 1MB,因此您应该使用链接器选项来增加它:

    /F (Set Stack Size)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-28
      • 2021-11-16
      • 1970-01-01
      相关资源
      最近更新 更多