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:
With C99 or later, you can parameterize the array size by using VLAs (variable length arrays):
If the size gets too large, you can use
malloc()instead, of course, but you have to make sure you free the space too:Obviously, you could allocate the
bufarray too if you really want to — I’m leaving it as an exercise for the reader.