1

This is my code:

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

int main()
{
    char Words[][20] = {"Dog", "Cat", "Table"};
    char command[20];

    do
    {
        printf("\nEnter command(Add, End): "); 
        /* input should be "Add" , write down a word, then "Add" again, then write down a new word. */
        scanf("%s", &command);

        if (strcmp(command, "Add") == 0)
        {
            int NumberOfWords = sizeof(Words) / sizeof(Words[0]);
            char NewWord[20];
            
            printf("Enter new word: ");
            scanf("%s", &NewWord);
            
            memcpy(Words[NumberOfWords], NewWord, sizeof(Words[NumberOfWords]));
            
            printf("\nTEST- the number of words is: %d\n" , NumberOfWords);
        }
        
    }while (strcmp(command, "End") != 0);
    
    printf("Program has ended!");
    return 0;
}

The problem is, NumberOfWords always stays 3 (AKA. the number of words is always 3) , even after supposedly adding value to Words[3] (which should make the number of words = 4). And that makes adding more words into the array Words not possible.

How do I fix that?

IrAM
  • 1,720
  • 5
  • 18
  • By incrementing it? – vmt Dec 28 '20 at 20:23
  • @ventsislav tsenov The array char Words[][20] = {"Dog", "Cat", "Table"}; has three elements. So you may not add a new element dynamically to the array. You could initially allocate the array dynamically and then reallocate it using the function realloc. – Vlad from Moscow Dec 28 '20 at 20:26
  • The easiest way is to declare `char Words[MAX][20]` where `MAX` is the maximum number of words you want to store – anotherOne Dec 28 '20 at 20:33
  • 1
    Anway `int NumberOfWords = sizeof(Words) / sizeof(Words[0]);` gives the number of elements in an array, not the *used* elements, which you have to keep count of yourself. – Weather Vane Dec 28 '20 at 20:34
  • 2
    `char command[20]; ... scanf("%s", &command);` should generate a warning. Save time, enable all warnings. – chux - Reinstate Monica Dec 28 '20 at 20:49
  • `scanf("%s", &command);` -> `scanf("%s", command);` -> `scanf` returns a pointer to and `command` is a pointer to a string. I'll leave error checking and buffer overruns for another day - but please look it up! – Ed Heal Dec 28 '20 at 21:05

2 Answers2

0

Well, to do this you need to choose between two options, created a huge array to store all kind of animals that might be added or you use dynamic arrays and memory allocation. In the code below I use memory allocation.

Basically I create a pointer to a pointer of chars, aka an array of strings and allocate space for 3 of them. I proceed to copy the initial string to those positions. After that, at each cyle you have to use realloc to increase the size of the allocated space.

Bear in mind that I am NOT checking for errors in malloc/realloc but you should always do that. Also, another good practice is to free the memory at the end. This code does that.

Edit: Forgot to mention that "scanf("%s", &command);" is no good. This generates a warning because command is already a pointer.


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

int main()
{
char **words=(char**)malloc(3*sizeof(char*));
char command[20];
int NumberOfWords = 3;


    words[0]=(char*)malloc(sizeof("Dog")+1);
    strcpy(words[0],"Dog");
    words[1]=(char*)malloc(sizeof("Cat")+1);
    strcpy(words[1],"Cat");
    words[2]=(char*)malloc(sizeof("Table")+1);
    strcpy(words[2],"Table");
do
{
    printf("\nEnter command(Add, End): "); 
    /* input should be "Add" , write down a word, then "Add" again, then write down a new word. */
    scanf("%s", command);
    if (strcmp(command, "Add") == 0)
    {
    
    char NewWord[20];
    printf("Enter new word: ");
    scanf("%s", NewWord);
    NumberOfWords++;
    words=realloc(words,sizeof(char*)*NumberOfWords);
    words[NumberOfWords-1]=(char*)malloc(sizeof(NewWord)+1);
    strcpy(words[NumberOfWords-1],NewWord);

    for(int i=0;i<NumberOfWords;i++)
    {
        printf("%s\n",words[i]);
    }
    printf("\nTEST- the number of words is: %d\n" , NumberOfWords);
    }

}
while (strcmp(command, "End") != 0);

    for(int i=0;i<NumberOfWords;i++)
    {
        free(words[i]);
    }
    free(words);

printf("Program has ended!");



return 0;
}

fuscati
  • 101
  • 7
0

If you want to increase the number of words dynamically, you can use char** and store as you wish.

In below example (Its a modified version of your code), I am limiting my self to just 5 words , displaying and freeing afterwards.

you can increase MAX_WORDS based on your need.

There are some more correction i have made w.r.t memcpy and scanf reading.

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

#define MAX_WORDS 5

int main()
{
    //char Words[][20] = {"Dog", "Cat", "Table"};
    char **Words = NULL;//[][20] = {"Dog", "Cat", "Table"};
    char command[20];
    
    int NumberOfWords = 0;
    
    if( ( Words = malloc(MAX_WORDS * sizeof (char*))) == NULL) 
    {
        printf("malloc failed");
        return -1;
    }
    
    do
    {
        printf("\nEnter command(Add, End): "); 
        /* input should be "Add" , write down a word, then "Add" again, then write down a new word. */
        if(1 != scanf("%s", command)) {
            printf("scanf error\n");
            //break to free memory in any allocated
            break;
        }

        if (strcmp(command, "Add") == 0)
        {
            //sizeof(Words) / sizeof(Words[0]);
            char NewWord[20];
            
            printf("Enter new word: ");
            
            if(1 != scanf("%s", NewWord)) {
                printf("scanf error\n");
                //break to free memory in any allocated
                break;
            }
            
            if( ( Words[NumberOfWords] = malloc(strlen(NewWord) +1)) == NULL)
            {
                printf("malloc failed for NewWord alloc\n");
                break;
            }
            strcpy(Words[NumberOfWords], NewWord);//, sizeof(Words[NumberOfWords]));
            
            // increase NumberOfWords 
            NumberOfWords += 1;
            printf("\nTEST- the number of words is: %d\n" , NumberOfWords);
            if(MAX_WORDS == NumberOfWords) {
                printf(" max words reached");
                break;
            }
        }
        
    }while (strcmp(command, "End") != 0);
    
    printf("\n words are: ");
    
    for(int i = 0; i< NumberOfWords; i++)
    {
        printf("%s ", Words[i]);
        free(Words[i]); 
        Words[i] = NULL;
    }
    
    free(Words); 
    Words = NULL;
    
    printf("Program has ended!");
    return 0;
}
IrAM
  • 1,720
  • 5
  • 18