Search code examples
cpointerscharmallocrealloc

How to realloc a *char[] inside a while loop?


Let's consider this array of char pointers :

char *lesMots[10];

Which is used inside a while loop :

while(fgets(buffer, TAILLE_BUFFER, fichier)!=NULL){
    token = strtok(buffer, s);
         while( token != NULL && token[0]!=13) 
        {               
            token[strlen(token)]='\0';
            *(lesMots + ligne)=strdup(token);
            ligne++;
            token = strtok(NULL, s);
        }
}

I'm trying to reallocate the memory of *lesMots[10] because it will crash later if the size is not equal or greater than 21.

I was thinking about reallocating the array as soon as ligne>=10 but it failed, that is why I dont show you my malloc and realloc test. Thank you for helping me.


Solution

  • If you need to be able to increase the size of the array, use a dynamically allocated array instead of a statically defined array.

    Instead of:

    char *lesMots[10];
    

    use

    char **lesMots = malloc(10*sizeof(*lesMots));