void getName(char* value)
{
const char *nameArray[] = { "bob", "billy", "jimbob", "boba fett", "chuck norris", "jimmy", "craig",
"howard", "leonard", "raj", "sheldon", "penny", "jenny", "sean", "amy", "bernadette",
"matthew", "olga", "ryan", "suanne", "darth vader", "luke", "spock", "kirk", "picard",
"michele", "randy", "suanne", "bruce lee", "garrett", "sophie", "gloria"};
int i = rand() % 33 + 1;
strcpy(value, nameArray[i]);
//value = nameArray[i];
}
I am trying to get a random name from this array and store it in value. I have debugged it and found that at strcpy, it crashes my program. If strcpy was commented out and value = nameArray[i]; wasn’t, then it wont do anything and leave the value empty. Please help!
There are only 32 strings in the array
nameArray. But when you do:ican go upto 33. So wheniis 33, you are invoking undefined behaviour.You probably want:
In C, remember array indexes vary from
0toN-1. NOT from 1 to N.Also make sure you have allocated memory for
valuebefore copying into it.