char数组初始值设定项错误中的多余元素

时间:2015-12-01 15:50:42

标签: c arrays char

我一直试图执行以下代码。但是,我一遍又一遍地遇到同样的错误而且我不知道为什么!

我的代码:

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

int main(void){

    int randomNum;
    char takenWords[4];
    char words[20]={"DOG", "CAT", "ELEPHANT", "CROCODILE", "HIPPOPOTAMUS", "TORTOISE", "TIGER", "FISH", "SEAGULL", "SEAL", "MONKEY", "KANGAROO", "ZEBRA", "GIRAFFE", "RABBIT", "HORSE", "PENGUIN", "BEAR", "SQUIRREL", "HAMSTER"};


    srand(time(NULL));

    for(int i=0; i<4; i++){
        do{
            randomNum = (rand()%20);
        takenWords[i]=words[randomNum];
        }while((strcmp(&words[randomNum], takenWords) == 0)&&((strcmp(&words[randomNum], &takenWords[i])==0)));
        printf("%s\n", &words[randomNum]);
    }
    getchar();
    return 0;
}

我已经计算了我在数组中输入的元素数量,它们不超过20!

另外,为什么我不断得到&#39;隐式转换失去整数精度错误&#39;?

4 个答案:

答案 0 :(得分:5)

我想你想要制作指针数组而不是字符数组。

试试这个:

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

int main(void){

    int randomNum;
    const char *takenWords[4];
    const char *words[20]={"DOG", "CAT", "ELEPHANT", "CROCODILE", "HIPPOPOTAMUS", "TORTOISE", "TIGER", "FISH", "SEAGULL", "SEAL", "MONKEY", "KANGAROO", "ZEBRA", "GIRAFFE", "RABBIT", "HORSE", "PENGUIN", "BEAR", "SQUIRREL", "HAMSTER"};


    srand(time(NULL));

    for(int i=0; i<4; i++){
        int dupe=0;
        do{
            randomNum = (rand()%20);
            takenWords[i]=words[randomNum];
            dupe=0;
            for(int j=0;j<i;j++){
                if(strcmp(words[randomNum],takenWords[j])==0)dupe=1;
            }
        }while(dupe);
        printf("%s\n", words[randomNum]);
    }
    getchar();
    return 0;
}

答案 1 :(得分:3)

char words[20]={"DOG", "CAT", "ELEPHANT", "CROCODILE", "HIPPOPOTAMUS", "TORTOISE", "TIGER", "FISH", "SEAGULL", "SEAL", "MONKEY", "KANGAROO", "ZEBRA", "GIRAFFE", "RABBIT", "HORSE", "PENGUIN", "BEAR", "SQUIRREL", "HAMSTER"};

查看您已仔细声明的数组。它包含什么?

字符串文字(即"DOG"和其他字符串文字)。

查看数组本身,声明它存储char

char words[20]

这就是错误。

要存储字符串文字,您需要pointer to char,即char *

由于您有一个字符串文字数组,因此需要一个char *

数组
char* words[20]={"DOG", "CAT", "ELEPHANT", "CROCODILE", "HIPPOPOTAMUS", "TORTOISE", "TIGER", "FISH", "SEAGULL", "SEAL", "MONKEY", "KANGAROO", "ZEBRA", "GIRAFFE", "RABBIT", "HORSE", "PENGUIN", "BEAR", "SQUIRREL", "HAMSTER"};

由于您还使用另一个数组指向字符串文字,因此以相同的方式声明它们

char* takenWords[4];

答案 2 :(得分:1)

这里的代码char words[20]是一个数组,用于保存20个字符但不包含20个不同字符串的单个字符串/单词。

  

然而,为了声明20个不同的字符串,请使用2D数组   方式字[20] [20]然后继续声明字符串/单词   您最多选择20个长度。

 char words[20][20]={"DOG", "CAT", "ELEPHANT", "CROCODILE", "HIPPOPOTAMUS", "TORTOISE", "TIGER", "FISH", "SEAGULL", "SEAL", "MONKEY", "KANGAROO", "ZEBRA", "GIRAFFE", "RABBIT", "HORSE", "PENGUIN", "BEAR", "SQUIRREL", "HAMSTER"};

注意: char words[20][20]表示一个数组,用于容纳20个字符串,最大长度为20个字符...

  

通常char words[m][n]其中m,n是整数,包含m个字符串   最大长度(n-1个字符)+(终止空字符)

答案 3 :(得分:0)

char arr [NUMBER_OF_STRING] [MAX_STRING_SIZE] 声明它的最大字符串大小