Complementary task for topic: 8

M Nemeth · 2023-08-29 15:21:04.629218'

Dynamic arrays: Array of dynamic strings

Dynamic arrays: Array of dynamic strings

Crate a C program, that can read as many words from user as it is requested. The read is done by a separate function. The strings (words) are stored in a dynamic array. Add 5 words and print them!

Hint: It is like the previous task, but the added element is again dynamic. Basically, it is not a problem, but we need to free() the inner strings before we can free the array.
Clearbuffer() is again needed after scanf the number of words.

Solution
#include 
void clear_buffer(){
    while((getchar())!='\n'){}
}

void Add_Word(char*** Arr,int* size){
    char* new_word=NULL;
    int len=1;
    char c;
    printf("give a new word:\n");
    while((c=getchar())!='\n'){
        new_word=(char *)realloc(new_word,(len+1)*sizeof(char));
        new_word[len-1]=c;
        new_word[len]='\0';
        len++;
    }
    *Arr=(char **)realloc(*Arr,((*size)+1)*sizeof(char*));

    (*Arr)[*size]=new_word; //precedence
    (*size)++;

    return; //No free needed because of realloc!

    }





int main()
{
    int size=0;
    char** Arr=NULL;
    int max_size;
    printf("how may words?");
    scanf("%d",&max_size);
    clear_buffer();
    for(int i=0;i
Explanation

< < previous    next > >