2015-06-04 23 views
0

我試圖從我的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是一些奇怪的外觀符號。

我到底做錯了什麼?

+3

其一,你的'test'陣列不夠長。它至少需要8個字符才能包含終止nulchar的空間。你的'問題'成員也一樣 – WhozCraig

+0

我不知道有一個終止nulchar。在改變'test'和'question'成員的大小之後,我確實得到了更可靠的輸出。我認爲這實際上可能是這裏的問題。 –

回答

2

您正在溢出內存緩衝區testquestion。它們的長度應該是8個字符而不是7個(0表示終止字符串的空格)。嘗試:

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

char test[8];

2

C/C++讀取以空終止符結束的字符串。

在您的情況,您複製內容到字符串緩衝區,這只是大到足以容納你的內容,而不是空終止,因此顯示操作認爲字符串繼續。

在這種情況下,由於提出的問題和答案是在存儲器中連續部分,這意味着它包括下一個問題和答案。

一對夫婦的方式來解決這個問題:

  1. 如果你可以使用C++和STL,使用的std :: string,而不是字符數組。
  2. 使您的緩衝區足夠大以容納所有內容,再加上緩衝區AND 使用受控操作員(如strncpy)將數據加載到緩衝區中。