Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excess elements in char array initializer error

Tags:

arrays

c

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!

My code:

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

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'?

like image 249
Alisinna Avatar asked Dec 01 '15 15:12

Alisinna


1 Answers

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

Try this:

#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;
}
like image 52
MikeCAT Avatar answered Sep 27 '22 18:09

MikeCAT