我怎么能写300个相同的字在一个数组中的C?

xv8emn3q  于 2023-01-01  发布在  其他
关注(0)|答案(1)|浏览(108)

如何写一个字300次在一个数组与代码在C中一样,例如。(wordwordword...)我是业余的。如果我写得不好,我很抱歉。

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

toiithl61#

有两个问题:
第一种方法是从未初始化的alotWord[i]复制,word是目的地,应该是相反的方法。
第二个问题是,你似乎忘记了C字符串实际上叫做*null-terminatedstrings *,一旦你修复了复制,你就永远不会以null-terminate结束你的字符串,你实际上没有空间来添加null-terminator。
也就是说,不要自己复制字符串,而是使用标准的strcpy

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

如果你想做的只是多次 * print * 这个单词,那么你根本不需要这个数组:

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

相关问题