Best way to allocate memory to a two-dimensional array in C?

前端 未结 3 426
天命终不由人
天命终不由人 2020-12-06 08:37

What is the best way to allocate memory to a two-d array in C,from both the perspectives : memory-management and speed ?

3条回答
  •  借酒劲吻你
    2020-12-06 09:12

    data_type (*mat)[size_2] = malloc(size_1 * size_2 * sizeof(data_type));
    

    That will allocate contiguous memory for an array of arrays ("2d array"). If you don't require ridiculous1 amounts of space, this is the way to go. You'll decrease memory fragmentation, increase cache friendliness and avoid too much overhead due to the use of malloc.


    1 For some (application specific) definition of ridiculous

提交回复
热议问题