从struct数组中输出随机元素

时间:2015-06-04 22:50:26

标签: c arrays random struct arduino

我试图从我的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是一些奇怪的符号。

我做错了什么?

2 个答案:

答案 0 :(得分:2)

C / C ++将字符串读取为以null终止符结尾。

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

在这种情况下,由于问题和答案位于记忆的连续部分,这意味着它包含下一个问题和答案。

有几种方法可以解决这个问题:

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

答案 1 :(得分:2)

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

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

char test[8];

相关问题