在堆栈上创建char **缓冲区的更好方法?

时间:2013-01-11 04:29:41

标签: c memory-management stack

我想在堆栈上创建一个char **字符数组。目前,我正在使用它,但我想知道是否有更好的方法:

char* buf[4];
char temp0[1024], temp1[1024], temp2[1024], temp3[1024];
buf[0] = temp0;
buf[1] = temp1;
buf[2] = temp2;
buf[3] = temp3;

编辑:为了更清楚,我不能简单地使用char buf[4][1024]。期望char指针数组的函数会崩溃,因为它是一种根本不同的数据类型。这就是我在堆上创建数组的方法:

char** buf = malloc(sizeof(char*) * 4);
for(int i = 0; i < 4; i++)
{
    buf[i] = malloc(sizeof(char) * 1024);
}

3 个答案:

答案 0 :(得分:2)

到目前为止发布的解决方案对于4个元素都是正常的;他们十分笨重,100人不会飞。我认为这可以更好地扩展:

enum { MAX_ROWS = 10, ROW_SIZE = 1024 };
char bigbuffer[MAX_ROWS][ROW_SIZE];
char *buf[MAX_ROWS];

for (int i = 0; i < MAX_ROWS; i++)
    buf[i] = bigbuffer[i];

...and off you go...

使用C99或更高版本,您可以使用VLA(可变长度数组)参数化数组大小:

void buffer_creation(int rows, int cols)
{
    char bigbuffer[rows][cols];
    char *buf[rows];

    for (int i = 0; i < rows; i++)
        buf[i] = bigbuffer[i];

    ...and off you go...
}

如果尺寸过大,当然可以使用malloc(),但你必须确保释放空间:

void buffer_creation(int rows, int cols)
{
    char *buf[rows];  // Probably won't stress the stack ever
    char *bigbuffer = malloc(rows * cols);
    if (bigbuffer != 0)
    {    
        for (int i = 0; i < rows; i++)
            buf[i] = &bigbuffer[i * cols];

        ...and off you go...
        free(bigbuffer);
    }
}

显然,如果你真的想要,也可以分配buf数组 - 我将它作为读者的练习。

答案 1 :(得分:1)

一个简单的char buf[4][1024];不一样好吗?

答案 2 :(得分:0)

稍微好一点的版本:

char temp0[1024], temp1[1024], temp2[1024], temp3[1024];
char *buf[4] = {temp0, temp1, temp2, temp3};
相关问题