Well, it seems you can not use vectors but normally that's exactly their purpose.
The problem with your solution is it's more C than C++, you use a char array whereas in C++ you should use a string
, and you use malloc
and realloc
whereas in C++ you should use new
.
Furthermore, you need to allocate memory for every level of indirection you have, so for a char **
you need at least 2 calls to malloc
. Here is a corrected solution (it's still almost C, not really C++, notice you don't use a single C++ header):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
//allocate a buffer of 10 pointers
size_t array_size = 10;
char ** array=(char **)malloc(array_size * sizeof(*array) );
if (!array)
return -1;
//now allocate the 10 pointers with a buffer to hold 42 characters
for (int i = 0; i < array_size; i++) {
array[i]= (char *)malloc( 42 * sizeof (*array[i]) );
if (!array[i])
return -1;
strcpy(array[i], "10");
}
//for some reason we need to increase array size by 1
++array_size;
array = (char **)realloc(array, array_size * sizeof(*array) );
array[array_size-1] = (char *)malloc(42 * sizeof(*array[array_size-1]) );
if (!array[array_size-1])
return -1;
strcpy(array[array_size-1], "12");
}