[英]Losing Value of Variable - C
我正在編寫一個文本編輯器,它使用ncurses來圖形表示一個數組key_strokes[]
。 它是一維的,所以我使用宏INDEX(y*maxx+x)
指向key_strokes
的當前位置( key_strokes[INDEX]
)。 y
和x
是函數getyx(stdscr, y, x)
返回的終端中的當前坐標, maxx
是函數getmaxyx(stdscr, maxy, maxx)
返回的每行中最大cols數。 該程序運行良好,直到我按退格鍵,由於某種原因, maxx
的值在到達下面的開關后設置為零。 這當然會拋出INDEX
將其限制為只有陣列的第一個“行”。
用戶的擊鍵被捕獲為int key_strokes
。 我用一個開關殼體,以檢查,看看它是否是一個arrowkey,退格,F12等INDEX
和maxx
被定義為,
#define INDEX (y*maxx+x)
unsigned int maxx = 0;
注意我也在使用cbreak(); noecho(); keypad(stdscr, TRUE);
cbreak(); noecho(); keypad(stdscr, TRUE);
。
case KEY_BACKSPACE:
if (INDEX >= 0)
{
for(i = INDEX; key_strokes[i] != '\0'; i++) {
key_strokes[i] = key_strokes[i+1];
}
if (total_count > 0) {
total_count--;
}
delch();
if (x == 0) {
move(y-1, maxx-1);
}
else {
move(y, x-1);
} refresh();
}
break;
你確定 key_strokes[]
是空終止的嗎?
'如果不是, for
循環會將內存中的所有內容復制到前一個單元格,直到達到0.如果maxx
或maxy
正好在0值之前,它們將被設置為0。
想象一下以下布局:
| key_strokes[0] | key_strokes[...] | key_strokes[n] | maxy | maxx | some_other_var |
| 'v' | 'i' | non-null garbage | 23 | 80 | '\0' |
在'i'之后按下backsapce后,它將是:
| key_strokes[0] | key_strokes[...] | key_strokes[n] | maxy | maxx | some_other_var |
| 'v' | non-null garbage | 23 | 80 | '\0' | '\0' |
這也可以解釋為什么當maxx
被聲明為const時,它的maxy
被設置為0(GCC不會將const
存儲在內存中的相同位置)。
為了確保key_strokes[]
以null結尾,我建議你將它添加到你的init部分:
memset(key_strokes, 0, sizeof(char) * size_of_key_strokes_array);
我看不到x和y的類型(即有符號或無符號),但是你計算得很有意思(y乘以無符號整數並添加x)。 這個表達的類型可能是什么? 可能它取決於y的類型。 檢查條件是否大於或等於零是否合理? (無符號值總是為零...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.