无法获取字符串数组来复制一个随机值

时间:2023-01-13 03:38:46
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!

我试图从这个数组中获取一个随机名称并将其存储在值中。我调试了它,发现在strcpy,它崩溃了我的程序。如果strcpy被注释掉并且value = nameArray [i];不是,那么它不会做任何事情,并将价值留空。请帮忙!

1 个解决方案

#1


4  

There are only 32 strings in the array nameArray. But when you do:

数组nameArray中只有32个字符串。但是当你这样做时:

int i = rand() % 33 + 1;

i can go upto 33. So when i is 33, you are invoking undefined behaviour.

我可以达到33.所以当我33岁时,你正在调用未定义的行为。

You probably want:

你可能想要:

int i = rand() % 32;

In C, remember array indexes vary from 0 to N-1. NOT from 1 to N.

在C中,记住数组索引从0到N-1不等。不是从1到N.

Also make sure you have allocated memory for value before copying into it.

还要确保在复制之前已为值分配了内存。

#1


4  

There are only 32 strings in the array nameArray. But when you do:

数组nameArray中只有32个字符串。但是当你这样做时:

int i = rand() % 33 + 1;

i can go upto 33. So when i is 33, you are invoking undefined behaviour.

我可以达到33.所以当我33岁时,你正在调用未定义的行为。

You probably want:

你可能想要:

int i = rand() % 32;

In C, remember array indexes vary from 0 to N-1. NOT from 1 to N.

在C中,记住数组索引从0到N-1不等。不是从1到N.

Also make sure you have allocated memory for value before copying into it.

还要确保在复制之前已为值分配了内存。