Allocating A Large (5000+) Array

后端 未结 3 922
一向
一向 2020-12-06 07:34

I am working on an application were there are three possible sizes for the data entered:

  • small: 1000 elements
  • medium= 5000 elements
  • large= 50
相关标签:
3条回答
  • 2020-12-06 07:47

    You can allocate such a big array on the heap:

    int *arr;
    arr = malloc (sizeof(int) * 500000);
    

    Don't forget to check that allocation succeded (if not - malloc returns NULL).

    And as pmg mentioned - since this array is not located in the stack, you have to free it once you finished working with it.

    0 讨论(0)
  • 2020-12-06 08:04

    Your stack can't hold that much data. You have to allocate big arrays on the heap as follows:

    int *array = malloc (sizeof(int)*size);
    

    As pmg pointed out remember to free your memory once your done.

    free(array);
    
    0 讨论(0)
  • 2020-12-06 08:08

    It's too big for the stack. Instead you need to allocate it on the heap with malloc.

    0 讨论(0)
提交回复
热议问题