i keep getting "exited, segmentation fault" for some reason. the code is supossed to output a random answer for any question and then keep in track of the questions using arrays. im really new to c++ and i got an assignment due really soon, plzz helpp:)
#include <iostream>
#include <string>
#include <array>
#include <ctime>
#include <cstdlib>
int main() {
srand(time(0));
std::string userquestion[0];
std::cout << "\nEnter Question: \n";
getline (std:: cin,userquestion[0]);
int k = 1;
do {
k++;
// creating and array for questions
int a = 1, b = 12, n;
n = findRandomRange(a,b);
std::string answers[] {"Don’t worry about that!", "That question has puzzled philosophers for centuries.", "I don't know. Sorry.", "Meditate on it, and the answer will come to you.", "I used to know the answer to that question, but I've forgotten.","That's a good question. You will find the answer in Chapter" ,};
// choosing a random array to answer the question
int randAnswer = rand() % 7;
std::cout << answers[randAnswer];
std::cout << "\nEnter Question: \n";
// assigning userquestion a array value
getline (std:: cin,userquestion[k]);
} while ( userquestion[k] != "goodbye");
return 0;
}
You get the segmentation violation because you've defined your userquestion array to have a size of 0 - that means it has no elements. I think I'm right in saying that's illegal.
Then, at line 12, you attempt to write to the first element of that array. Since the array has no elements, you're writing to memory that hasn't been allocated for writing to. This is undefined behaviour, and causes your crash.
it may be, but it compiles on a lot of compilers. I am not sure (and I am not going to look up the legality of nonsense).
be glad it crashed. if it had worked, the usual behavior is to put the bytes you wrote on top of some other thing in memory, causing odd behavior that is very hard to diagnose. Nothing like saying x[invalid] = 1234; and having variable y get a new value.
It won't compile on any mainstream compiler (if C++ conformance is enabled).
1 2 3 4 5 6 7 8 9
#include <string>
int main()
{
// GNU: **** error: ISO C++ forbids zero-size array
// LLVM: **** error: zero size arrays are an extension
// Microsoft: **** error: cannot allocate an array of constant size 0
std::string userquestion[0];
}