cpointersmatrixragged

ragged *char 2d array with realloc


i was wondering how do i create a ragget 2d string(char*)array in c . (my example code looks like this)

    int j = 1;
    char **array = null;
   ... read string...
   *array = (char *) realloc(sizeof(char *) * j);
   j++;
(sirAvertisment[j] = (char **) realloc((*sirAvertisment)[j],sizeof(char *) * strlen(somearray[i]))

for example i want it

  1. A L F A B E T
  2. A P P L E
  3. K I D
  4. S E M A P H O R E S

but with pointers so when i read 1 row of a matrix i get the word complete


Solution

  • Your general idea is right, but you have some details wrong.

    You shouldn't indirect through the pointers when assigning the allocations.

    You need to add 1 to strlen() when allocating, to allow foom for the trailing null.

    You shouldn't cast the result of realloc.

    You should check that realloc() is successful before reassigning the original pointer.

    Use malloc() when you're allocating memory for the new element you added to the array; realloc() should only be used when the pointer has already been initialized.

    char **array = null;
    ...
    char **new_array = realloc(array, sizeof(char *) * j);
    if (!new_array) {
        printf("Allocation failed!\n");
        exit(1);
    }
    array = new_array;
    array[j] = malloc(strlen(somearray[i]) + 1);
    strcpy(array[j], somearray[i]);
    j++;