'I am trying to print a random character from an array by using rand()
Hello all I want to write a program to randomly choose a character from an array, so far I have come up with this code. I get an Error message help...Thread 1: EXC_BAD_ACCESS (code=1, address=0x48) at the last printf()
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int lower = 1, upper = 6;
int test;
srand((unsigned int)time(0));
char* placeArray[]={"Renti","Mosxato","Tavros","Kallithea","Petralona","Thisio"};
int i, num;
for (i=0;i<6;i++){
num=(rand() % (upper - lower + 1)) + lower;
test=(int)num;
printf("%d ",num);
printf("%s\n",placeArray[num]);
}
return 0;
}
Solution 1:[1]
num should be num-1 in the last printf, because the range of the elements in the array is 0 to 5, as shown below
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int lower = 1, upper = 6;
int test;
srand((unsigned int)time(0));
char * placeArray[]= {"Renti", "Mosxato", "Tavros", "Kallithea", "Petralona", "Thisio"};
int i, num;
for (i = 0; i < 6; i++){
num = (rand() % (upper - lower + 1)) + lower;
test = (int)num;
printf("%d ", num);
printf("%s\n", placeArray[num - 1]);
}
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
