Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i write 300 of the same word in an array in C?

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];
        }
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading