【问题标题】:Output random element from struct array从结构数组中输出随机元素
【发布时间】:2015-08-19 18:07:47
【问题描述】:

我试图从我的 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

我做错了什么?

【问题讨论】:

  • 一方面,您的test 数组不够长。它需要至少 8 个字符来包含终止 nulchar 的空间。您的question 成员也是如此
  • 我不知道有一个终止的 nulchar。更改testquestion 成员的大小后,我确实得到了一些更可靠的输出。我认为这实际上可能是这里的问题。

标签: c arrays random struct arduino


【解决方案1】:

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

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

char test[8];

【讨论】:

    【解决方案2】:

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

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

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

    解决这个问题的几种方法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2013-11-14
      • 2016-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多