Home > Software engineering >  How to dynamically allocate memory for words stored in an array?
How to dynamically allocate memory for words stored in an array?

Time:04-02

I input words one by one from the screen and send them to an array. I can, of course, immediately allocate large memory for the array, but I would like to allocate memory for this dynamically.

For example I have an array words. First, I allocate a little memory for it char *words = malloc(capacity) , where capacity = 15 for example. ...enter words from the screen... . All allocated memory is full and I allocate more memory for further work char *tmp = realloc(words, capacity*2). Probably,I understand how it works. But I can't figure out how to write it. That is, how to enter these words and send them to an array. Could you describe in detail how I should do this?

Example:

I input words from the screen side left ball rich and at the end I have an array *arr = ["side", "left", "ball", "rich"]

CodePudding user response:

You need to have a arry of pointers where each index stores a word. Also attention has to be given to release the memory.

Snippet as follows,

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

int main()
{
    int size = 3;
    char word[30];
    
    char **word_list =  malloc(sizeof(word_list) * size);
    
    printf("Enter %d Words\n",size);
    
    for(int i =0; i<size;   i){
    
        scanf("0s",word);
        
        int word_size = strlen(word) 1;
        
        word_list[i] = malloc(word_size);
        
        strncpy(word_list[i],word,word_size);
    }
    
    printf("\nEntered words are\n");

    for(int i=0; i<size;   i){
        printf("%s ",word_list[i]);
    }
    
    
    //resizing the capacity of the array
    {
        int resize;
        printf("\nresize array size to: ");
        scanf("%d",&resize);
        
        if(size<resize){
            for(int i=size-1; i>=resize; --i)
                free(word_list[i]);
        }        
        
        word_list = realloc(word_list, sizeof(word_list) * resize);
        
        if(resize > size)
            printf("Enter %d Words \n",resize-size);
        
        for(int i =size; i<resize;   i){
        
            scanf("0s",word);
            
            int word_size = strlen(word) 1;
            
            word_list[i] = malloc(word_size);
            
            strncpy(word_list[i],word,word_size);
        }
        
        size = resize;
    }
    
    printf("Current words are\n");
    for(int i=0; i<size;   i){
        printf("%s ",word_list[i]);
    }
    
    
    //Memory deallocation
    for(int i=0; i<size;   i){
        free(word_list[i]);
    }
    
    free(word_list);
    
    
    return 0;
}

DEMO

  • Related