Nicer way to create a char** buffer on the stack?
I want to create a char** character array on the stack. Currently, I'm using this, but I wonder if there is a nicer way:
char* buf[4];
char temp0[1024], temp1[1024], temp2[1024], temp3[1024];
buf[0] = temp0;
buf[1] = temp1;
buf[2] = temp2;
buf[3] = temp3;
EDIT: To be more clear, I can not simply use char buf[4][1024]
. A function expecting an array of char pointers would crash, as it's a fundamentally different data type. This is how I would create the array on the heap:
char** buf = malloc(sizeof(char*) * 4);
for(int i = 0; i < 4; i++)
{
buf[i] = malloc(sizeof(char) * 1024);
}
The solutions posted so far are both OK for 4 elements; for 10 they're clunky, and for 100 not going to fly. I think this can scale better:
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...
With C99 or later, you can parameterize the array size by using VLAs (variable length arrays):
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...
}
If the size gets too large, you can use malloc()
instead, of course, but you have to make sure you free the space too:
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);
}
}
Obviously, you could allocate the buf
array too if you really want to — I'm leaving it as an exercise for the reader.
Shouldnt a simple char buf[4][1024];
work just as good?
稍微好一些的版本:
char temp0[1024], temp1[1024], temp2[1024], temp3[1024];
char *buf[4] = {temp0, temp1, temp2, temp3};
链接地址: http://www.djcxy.com/p/79252.html
上一篇: 内存分配量堆栈和堆(c)