从结构数组中输出随机元素

Output random element from struct array

我正在尝试从我的 Arduino 上的结构数组中输出一个随机元素。结构看起来像这样

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

我在我的循环中调用了一个方法,该方法包含一堆问题和答案,然后应该选择一个随机问题并将其显示在显示器上。该方法看起来像这样

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;
    }

我不确定我做错了什么,但即使不是上面的使用 lcd.print(problems[0].question); 显示也显示来自结构数组的多个问题。例如,上面的显示显示 49 x 27+X31 x 35<- 其中 X 是一些看起来很奇怪的符号。

我做错了什么?

C/C++ 读取以空终止符结尾的字符串。

在您的情况下,您已将内容复制到一个字符串缓冲区中,该缓冲区的大小仅足以容纳您的内容,但不能容纳空终止符,因此显示操作认为字符串会继续。

在这种情况下,由于问题和答案在内存中是连续的,这意味着它包含下一个问题和答案。

一些补救方法:

  1. 如果可以使用 C++ 和 STL,请使用 std::string 而不是字符数组。
  2. 使您的缓冲区足够大以容纳所有内容,加上缓冲区和 使用受控运算符,例如 strncpy 将数据加载到缓冲区中。

您正在溢出内存缓冲区 testquestion。它们的长度应该是 8 个字符而不是 7 个(space 表示 0 终止字符串)。尝试:

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

char test[8];