There is an array char *Names[] = { "Alexandr", "Kostya", "Roman" }; trying to make a random name function and write it to another array

 int _tmain(int argc, _TCHAR* argv[]) { char *Empty[100]; char *Names[] = { "Alexandr", "Kostya", "Roman" }; for (int i = 0; i < 3; i++) { Empty[i] = Names[rand() % 3 + 1]; cout << Empty[i]; } return 0; } 

But it gives an error. Tell me how to set? Thank you

Closed due to the fact that off-topic participants Abyx , Vladimir Martyanov , aleksandr barakin , D-side , VenZell 23 Mar '16 at 13:47 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • “Questions asking for help with debugging (“ why does this code not work? ”) Should include the desired behavior, a specific problem or error, and a minimum code for playing it right in the question . Questions without an explicit description of the problem are useless for other visitors. See How to create minimal, self-sufficient and reproducible example . " - Abyx, Vladimir Martyanov, D-side, VenZell
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • 3
    Mistake propose to guess? - ixSci

2 answers 2

To begin with, rand()%3+1 gives values ​​from 1 to 3, and the elements of the arrays start counting from 0, so Names[3] you simply do not exist.

Everything else will work ... but I have no confidence that this code does exactly what you want. Although it is quite efficient - if you remove +1 .

  • Thank. Another question is, how do I get rid of duplicate names? - Alexandr T

What would each time a random value be different, you can apply srand(time(NULL));

 #include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { srand(time(NULL)); char *Empty[100]; char *Names[] = { "Alexandr", "Kostya", "Roman" }; for (int i = 0; i < 3; ++i) { Empty[i] = Names[rand()%3]; printf("%s\n", Empty[i]); } } 
  • Thanks, helped. - Alexandr T
  • Thank. Another question is, how do I get rid of duplicate names? - Alexandr T
  • @AlexandrT I answered this question in the appropriate place :) - Harry