0

I've been searching for an answer to this for quite some time now, to no avail. So, as my final effort I will ask the public.

string* random_ai_car() {
srand((unsigned)time(NULL));
int random = rand() % 6 + 1;
 string ai_color[6] { "Pink","blue","purple","black","grey","silver"};
 string *get_car;
 get_car = &ai_color[random];
return get_car;}

I know that I probably do not need the pointers. It was kind of silly to try and use them for this function. How I want this program to function is that it will generate a random car color and then I could use it in my cout<< in my main method. Every time I try to use it in main() it just either gives me nothing at all or, in cout<< it gives me about 6 digits of numbers. My question is, am I returning the wrong value to actually get an output? or am I not using the function with the string properly?

update:

So, I diced into a bit more of what was being said about my poor beginner skills, so I researched different things about how to call within the function. I still don't quite understand how that works exactly. Can someone provide my with a link to learn more about why and how you should properly call a function and or return a function? I did happen to fix the problem, not quite how I wanted to do it though

string* random_ai_car() {
int random = rand() % 5;
 string ai_color[6] { "Pink","blue","purple","black","grey","silver"};
 string *get_car;
     get_car = new string;
 *get_car = ai_color[random];
 return get_car;
  • 2
    The function has undefined behavior, because it returns the address of a local variable. – Rakete1111 Jul 08 '16 at 01:04
  • 1
    @Rakete1111: Answers do not go in the comments section. I don't know how many more times I have to say it before it'll sink in. – Lightness Races in Orbit Jul 08 '16 at 01:06
  • 2
    Besides being a dangling pointer, adding insult to injury this code will attempt to retrieve, randomly, element 1 through 6 from an array that contains elements 0 through 5. 1/6th of a time, this will result in undefined behavior, and a likely crash. – Sam Varshavchik Jul 08 '16 at 01:08
  • Warning: the above code also has the smell of repeated calls to `srand`. Seeding the RNG is computationally expensive, almost always unnecessary, and very often produces random numbers of poor quality. – user4581301 Jul 08 '16 at 01:13
  • Ditch the pointer: `string random_ai_car() {`, and then `return ai_color[random];`. (And you should only call `srand` once – do it early in `main`.) – molbdnilo Jul 08 '16 at 06:32

0 Answers0