Mar 10, 2014 at 7:23pm UTC
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 Mar 10, 2014 at 7:24pm UTC
Mar 10, 2014 at 8:44pm UTC
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.
Mar 10, 2014 at 8:47pm UTC
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 Mar 10, 2014 at 8:48pm UTC
Mar 10, 2014 at 8:50pm UTC
Ah OK - I misread that. Thanks EssGeEich.
Mar 11, 2014 at 3:16am UTC
Silly me... Thanks EssGeEich ..