在C动二维数组分配 [英] Dynamic 2D Array allocation in C

查看:131
本文介绍了在C动二维数组分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该怎么用C分配动态数组?目前,我有一个功能,我编写的名为 malloc2D ,看起来像这样:

How I should allocate dynamic arrays in C? Currently I have a function I wrote called malloc2D that looks like this:

void* malloc2D(size_t unitSize, uint firstCount, uint secondCount)
{
    void** pointer = malloc(sizeof(id) * firstCount);
    for (int i =0; i < firstCount; i ++){
        pointer[i] = malloc(unitSize * secondCount);
    }
    return pointer;
}

它工作得很好,但是我被告知,它把很多应变上的内存分配分开。什么是做到这一点的最好或最常规的方法是什么?

It works fine however I have been told that it puts a lot of strain on the memory allocating separately. What is the best or most conventional way to do this?

推荐答案

您可以分配数组作为这样一个连续的集团。假设你想要整型:

You can allocate the array as a contiguous bloc like this. Suppose you want ints:

int (*arr)[secondCount] = malloc( sizeof(int[firstCount][secondCount]) );

您可以隐藏这里面需要的类型名称作为宏参数宏的背后,虽然code是很简单,这是不是真的有必要。

You could hide this behind a macro which takes the typename as a macro argument, although the code is simple enough that that is not really necessary.

这篇关于在C动二维数组分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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