char数组初始化程序中的多余元素错误 [英] Excess elements in char array initializer error

查看:296
本文介绍了char数组初始化程序中的多余元素错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试执行以下代码。.但是,我一遍又一遍地得到相同的错误,我不知道为什么!

I've been trying to execute the following code.. However, I keep getting the same errors over and over again and I don't know why!

我的代码:

#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!

I have counted the number of elements which I entered in the array and they do not exceed 20!

为什么我仍然不断收到隐式转换丢失整数精度错误的信息?

Also, why do I keep getting the 'Implicit conversion loses integer precision error'?

推荐答案

我想您想创建一个指针数组而不是字符数组。

I guess you want to make arrays of pointers instead of arrays of characters.

尝试以下操作:

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

这篇关于char数组初始化程序中的多余元素错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆