Dynamique de la mémoire/realloc tableau de chaînes

Cherche à créer un tableau dynamique de la chaîne de valeurs.

Dans l'exemple de code ci-dessous, l'intention était d'une nouvelle matrice de l'élément à ajouter (realloc) et une nouvelle chaîne de caractères ("string " 3") pour être ajouté dans le tableau au moment de l'exécution.

J'imagine que le problème est soit de la mauvaise utilisation des pointeurs et/ou quelque chose de mal avec l'realloc logique?

Reconnaissant de toute aide.

La sortie réelle je suis arriver:

Before: 
Array[0]: string 1
Array[1]: string 2
After: 
Array[0]: string 1
Array[1]: string 2

Le code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char **myArray;

main(int argc, char *argv[])
{
    int i = 0;
    myArray = malloc(2 * sizeof(char*));
    int arrayIndexs = sizeof(*myArray) / sizeof(char*);

    //Allocate memory for each [x]
    for (i = 0; i <= arrayIndexs; i++)
        myArray[i] = malloc(254 * sizeof(char*));
    //Populate initial values
    if(myArray != NULL)
    {
        strcpy(myArray[0], "string 1");
        strcpy(myArray[1], "string 2");
    }
    //Print out array values
    printf("Before: \n");
    for (i = 0; i <= arrayIndexs; i++)
        printf("Array[%d]: %s\n",i, myArray[i]);

    //Expand array to allow one additional item in the array
    myArray = (char **)realloc(myArray, sizeof(myArray)*sizeof(char*));

    //Allocate memory for the new string item in the array
    myArray[arrayIndexs+1] = malloc(254 * sizeof(char*));

    //Populate a new value in the array
    strcpy(myArray[arrayIndexs+1], "string 3"); //

    arrayIndexs = sizeof(*myArray)/sizeof(char*);

    //Print out array values
    printf("After: \n");
    for (i = 0; i <= arrayIndexs; i++)
        printf("Array[%d]: %s\n",i, myArray[i]);
}
Si vous jamais trouvez en essayant d'utiliser sizeof() pour tout, qui est de taille moyenne dynamiquement, vous le faites mal. Gardez cela à l'esprit.

OriginalL'auteur MrDB | 2014-02-22