What I am trying to do is to have the code look into the array words, randomly pick a word from that array, and place it within the array test. It should do this 3 times, and then print what is within the array test.
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <string>
#include <time.h>
#include <windows.h>
using namespace std;
using std::cout;
using std::cin;
using std::endl;
int main() {
int guess;
string words[] = {"Me", "You", "Everyone", "Mom", "Dad"};
string test[3];
for (guess = 1; guess <= 3; guess++) {
string word = words[rand() % 4];
test[guess] = word;
}
if (guess == 3) {
cout << words << endl;
}
cin.get();
return 0;
}
However, when I run the code, I get this error:
Exception thrown at 0x0F2550D9 (vcruntime140d.dll) in ConsoleApplication10.exe: 0xC0000005: Access violation writing location 0xCCCCCCCC.
What am I doing to cause this error, and how do I fix it?
In C++ and pretty much all other programming languages I know of, arrays use this thing called 0 indexing. That means the index of the elements starts counting from 0. The first element is indexed 0, second 1, and so on. If you have an array of size n the last element is indexed n - 1.
In your code, the array
test
has a size of three. The elements have index 0, 1, and 2. Your loop goes from 1 to 3, so the last time in the loop you tried to access the element past the end of the array, causing an access violation. You should instead loop from 0 to 2 like this:By the way, there are a lot of other problems in your code:
You never set the seed for
rand()
, so every time you run the program it will output the same thing.You used
rand() % 4
to generate random numbers, which will give you numbers from 0 to 3, therefore, ignoring the last word.The last if statement makes no sense at all since you are checking if guess is equal to 3, which it will never be (it must be larger than 3 for the loop to break), and then you tried to output the whole array
words
, which does not work. You should use a loop to output each element oftest
notguess
.Code with all the changes:
I would recommend getting a good book.
You can merge the two loops without even storing the words guessed:
Note that in general, using the
std::rand()
function is not recommended since it tends to result in low quality random numbers. It is best to use the newer random number generators in the standard library instead.