gpt4 book ai didi

c - char 数组初始值设定项错误中元素过多

转载 作者:行者123 更新时间:2023-12-02 18:18:13 24 4
gpt4 key购买 nike

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

我的代码:

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

此外,为什么我不断收到“隐式转换丢失整数精度错误”?

最佳答案

我猜你想创建指针数组而不是字符数组。

试试这个:

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

关于c - char 数组初始值设定项错误中元素过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34024433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com