I am trying to get 10 random numbers and collect them in a char array to get a random customer ID But it's giving this warning. I couldn't fix it whatever I do. Can you help?
char customerid(){
char id[100];
char b[50];
srand(time(0));
for(int i=0; i<10; i++){
int n = rand() % 10;
char c = n + 48;
strcat(id, c); //here is the problem
}
printf("%s", id[100]);
return id[100];
}
Here is my second trial:
char customerid(){
char id[100];
for(int i=0; i<10; i++){
int n = rand() % 10;
char* c = (char*)n + '0';
strcat(id, c);
}
printf("%s", id[100]);
return id[100];
} But it still gives the same error. Can you correct the code? How do we add an integer or char to a string array?
You've basically done wrong everything that can be done wrong.
strcat
is the wrong function, you don't want to concat two strings, instead you want to construct a string character by character.char customerid(...
is pointless, it returns a single character which is not what you want.printf("%s", id[100]);
prints element 100 (which by the way doesn't exist, because you array has only 100 elements and array index start at 0).srand
each and every time doesn't make sense. Read this SO article for an explanation: srand() — why call it only once?. BTW, for debugging purposes it can be useful not to call srand
at all, then you will always get the same sequence of random numbers.You probably want this:
void customerid(char *id) {
int i;
for (i = 0; i < 10; i++) {
id[i] = rand() % 10 + '0';
}
id[i] = 0; // put the null string terminator
}
int main()
{
srand(time(0));
for (int i = 0; i < 10; i++) // generate 10 different ids
{
char id[100]; // id will contain the random customer id
customerid(id); // call customerid and tell it to fill the id array
printf("%s\n", id); // print the customer id
}
}
I suggest you read the chapter dealing with pointers, the one dealing with strings and the one dealing with arrays in your C text book.