rand() generating segmentation fault

Why would this code produce segmentation fault :

/*
#include<iostream>

#include <stdlib.h>
#include <ctime>
using namespace std;

int main()
{
int i=0;
srand(time(0));
string location[]={"LA","delhi","Las Vegas"};

for (i=0;i<20;i++)
{
cout<<location[rand()%4]<<"\n";
}

}
*/
Last edited on
I stand to be corrected here, but it looks like you've initialized an array with 3 elements and then are trying to access 20 elements of the array, memory locations that don't all exist, through the for loop.
Nah, every loop iteration he's accessing from #0 to #3 element, but the #3 element doesn't exist.

Change from 4 to 3, near that rand.
Last edited on
Ah OK - I misread that. Thanks EssGeEich.
Silly me... Thanks EssGeEich ..
Topic archived. No new replies allowed.