1

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?

anothertest
  • 979
  • 1
  • 9
  • 24

1 Answers1

2

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");
}
Étienne
  • 4,773
  • 2
  • 33
  • 58
  • Thank you, your answer is very clear. Unfortunately I cannot use std::string...I don't know the size of the char array I am going to add in the array. So the best option would be to create my own string class and make a string array: string* array? – anothertest Apr 19 '14 at 14:43
  • Yes, you can create your own string class and use realloc in there. It is surprising that you are not allowed to use vector and string, usually it is the opposite, students are forbidden to use char arrays and malloc since it is a bad habit to do that in C++. – Étienne Apr 19 '14 at 14:48
  • In this homework I have to deal with shallow and deep copies. Stl containers already have it implemented, that's I cannot use them. Thank you. – anothertest Apr 19 '14 at 14:51
  • correct me if I'm wrong, but isn't `sizeof(*array[i])` just going to be 1, since it's a `char`? – galois Dec 25 '15 at 06:18