problem initializing large double array

前端 未结 2 398
轮回少年
轮回少年 2021-01-15 16:29

Silly question from a new C programmer... I get a segmentation fault in the following code:

#include 
int main(void)
{
double YRaw[4000000]={0         


        
2条回答
  •  难免孤独
    2021-01-15 16:52

    You tried to declare the entire array on the stack. Even if you have a terabyte of RAM, only a small, fixed portion of it is going to be dedicated to stack space. Large amounts of data need to be allocated on the heap, using malloc:

    #include 
    int main(void)
    {
      double* YRaw = malloc(4000000 * sizeof(double));
      memset(YRaw, 0, 4000000 * sizeof(double));
    
      /* ... use it ... */
    
      free(YRaw); /* Give the memory back to the system when you're done */
    
      return 0;
    }
    

    See also: "What and where are the stack and heap?"

提交回复
热议问题