Home > Back-end >  How can i write 300 of the same word in an array in C?
How can i write 300 of the same word in an array in C?

Time:12-31

How to write a word 300 times in an array with code in C like for ex. (wordwordword....) I am amateur. If i wrote bad i am sorry.

int main()
{
    int i,j,k=0,boyut;
    char word[10]={"word"};
    char alotWord[300][4];

    for(i=0;i<300;i  )
    {
        for(j=0;j<4;j  )
        {
           word[j]=alotWord[i][j];
        }
    }

CodePudding user response:

There are two problems:

The first is that you copy from the uninitialized alotWord[i], with word being the destination. It should be the opposite way around.

The second problem is that you seem to forget that C strings are really called null-terminated strings. Once you fix the copying you never null-terminate your strings. You don't actually have space for adding the null-terminator.

With that said, don't do string copying yourself, use the standard strcpy instead:

char alotWord[300][sizeof word];  // Use sizeof to make sure that the word fits

for(i=0;i<300;i  )
{
    // Copy from word into alotWord[i]
    strcpy(alotWord[i], word);
}

And if all you want to do is print the word a lot of times you don't need the array at all:

for(i=0;i<300;i  )
{
    printf("%s", word);
}
  • Related