我们如何分配使用malloc的一个语句中2-D阵列 [英] How do we allocate a 2-D array using One malloc statement

查看:82
本文介绍了我们如何分配使用malloc的一个语句中2-D阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人问我在接受采访时我如何分配一个二维数组以下是我的解决方案吧。

I have been asked in an interview how do i allocate a 2-D array and below was my solution to it.

#include <stdlib.h>

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

    for(i = 0; i < nrows; i++)
        {
        array[i] = malloc(ncolumns * sizeof(int));
        if(array[i] == NULL)
            {
            fprintf(stderr, "out of memory\n");
            exit or return
            }
        }

我想我已经做了很好的工作,但后来他问我使用一个malloc的声明不two.I没有任何想法如何实现它做到这一点。

I thought I have done good job but then he asked me to do it using one malloc statement not two.I don't have any idea how to achieve it.

任何人都可以提出我一些想法做单的malloc?

Can anyone suggest me some idea to do it in single malloc?

推荐答案

只是计算的内存需要为 NROWS 行指针总量和实际数据,说起来,做一个呼叫:

Just compute the total amount of memory needed for both nrows row-pointers, and the actual data, add it all up, and do a single call:

int **array = malloc(nrows * sizeof *array + (nrows * (ncolumns * sizeof **array));

如果您认为这看起来太复杂,你可以拆分它,并通过命名尺寸前pression的不同方面使它有点自我记录:

If you think this looks too complex, you can split it up and make it a bit self-documenting by naming the different terms of the size expression:

int **array; /* Declare this first so we can use it with sizeof. */
const size_t row_pointers_bytes = nrows * sizeof *array;
const size_t row_elements_bytes = ncolumns * sizeof **array;
array = malloc(row_pointers_bytes + nrows * row_elements_bytes);

您则需要通过和初始化行指针,以便在该特定行中的第一个元素的每一行的指针指向:

You then need to go through and initialize the row pointers so that each row's pointer points at the first element for that particular row:

size_t i;
int *data = array + nrows;
for(i = 0; i < nrows; i++)
  array[i] = data + i * ncolumns;

请注意所产生的结构,你会得到什么,如果你做的是例如从微妙的不同 int数组[NROWS] [ncolumns] ,因为我们有明确的行指针,这意味着对于分配一个这样的数组,还有所有行具有相同数量的没有真正的需求列。

Note that the resulting structure is subtly different from what you get if you do e.g. int array[nrows][ncolumns], because we have explicit row pointers, meaning that for an array allocated like this, there's no real requirement that all rows have the same number of columns.

这篇关于我们如何分配使用malloc的一个语句中2-D阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆