Daniel Jørgensen
Daniel Jørgensen

Reputation: 1202

Output random element from struct array

Im trying to output a random element from an array of structs on my Arduino. The struct looks like this

struct questionStructure {
    char question[7];
    int answer;
};

I call a method in my loop that holds a bunch of questions with answers and a random question is then supposed to be selected and shown on the display. That method looks like this

bool questionIsShown = false;
void randomQuestion()
{
    int random;
    struct questionStructure problems[4];
    char test[7];

    strcpy(test, "49 x 27");
    strcpy(problems[0].question, test);
    problems[0].answer = 1323;

    strcpy(test, "31 x 35");
    strcpy(problems[1].question, test); 
    problems[1].answer = 1085;

    strcpy(test, "47 x 37");
    strcpy(problems[2].question, test); 
    problems[2].answer = 1739;

    strcpy(test, "46 x 15");
    strcpy(problems[3].question, test); 
    problems[3].answer = 690;

    strcpy(test, "24 x 29");
    strcpy(problems[4].question, test); 
    problems[4].answer = 696;

    if(questionIsShown==false) {
        random = rand() % 4 + 0;
        lcd.setCursor(0,1);
        lcd.print(problems[random].question);
        questionIsShown=true;
    }

Im not sure what im doing wrong, but even if instead of the above use lcd.print(problems[0].question); the display shows multiple questions from the struct array. As an example, with the above the display shows 49 x 27+X31 x 35<- Where the X is some wierd looking symbol.

What am i doing wrong?

Upvotes: 0

Views: 969

Answers (2)

Maciej
Maciej

Reputation: 9605

You are overflowing memory buffers test and question. Their length should be 8 chars not 7 (space for 0 terminating string). Try:

struct questionStructure {
    char question[8];
    int answer;
};

and char test[8];

Upvotes: 2

JohnMcG
JohnMcG

Reputation: 8805

C/C++ read strings as ending with a null terminator.

In your case, you've copied content into a string buffer that is only big enough to hold your content, but not the null terminator, so the display operation thinks the string continues.

In this case, since the questions and answer are in contiguous parts of memory, this means that it includes the next question and answer.

A couple of ways to remedy this:

  1. If you can use C++ and the STL, use std::string rather than character arrays.
  2. Make your buffers big enough to hold all the content, plus the buffer AND use controlled operators, such as strncpy to load the data into your buffers.

Upvotes: 2

Related Questions