Question

I have to store some char arrays in an array. But I don't know how many of them I will have to store.

What would be the best: initializing my array with a small size (like 1) and then realloc everything? How am I supposed to use realloc or malloc?

I cannot use vectors nor stl containers nor strings unfortunately. Increasing the size of a vector is very easy and I tried to understand malloc and realloc but I don't...

char ** array=(char**)malloc(10*sizeof(char*));
for (int i=0;i<10;i++)
    array[i]="10";
array=(char **)realloc(array,(sizeof(array)+1)*sizeof(char*));
array[10]="12";

I understood the basic principle yes. Is it in this way?

Était-ce utile?

La solution

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");
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top