c - 失去变量的值(value) - C

标签 c ncurses

  • 编译器:gcc 4.5.2
  • 终端:Xterm
  • 操作系统:Linux(x86)
  • Ncurses 5.9

我正在编写一个文本编辑器,它使用 ncurses 以图形方式表示数组 key_strokes[] .它是一维的,所以我使用宏 INDEX(y*maxx+x)指向key_strokes中的当前位置(key_strokes[INDEX])。 yx是函数返回的终端中的当前坐标 getyx(stdscr, y, x)maxx是函数 getmaxyx(stdscr, maxy, maxx) 返回的每一行中可以包含的最大列数.该程序运行良好,直到我按退格键,由于某种原因 maxx 的值到达下面的开关后设置为零。这当然会引发INDEX将其限制为仅数组的第一“行”。

用户的击键被捕获为int key_strokes .我使用开关盒来检查它是否是箭头键、退格键、F12 等。INDEXmaxx定义为,

#define INDEX (y*maxx+x)
unsigned int maxx = 0;

注意我也在使用 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'后按退格键后,它将是:

| key_strokes[0] | key_strokes[...] |   key_strokes[n] | maxy | maxx | some_other_var |
|            'v' | non-null garbage |               23 |   80 | '\0' |           '\0' |

这也可以解释为什么 maxymaxx 声明为 const 时设置为 0(GCC 不存储 const在内存中的同一位置)。

为确保 key_strokes[] 以 null 结尾,我建议您将其添加到您的初始化部分:

memset(key_strokes, 0, sizeof(char) * size_of_key_strokes_array);

关于c - 失去变量的值(value) - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13409755/

相关文章:

python - nodelay() 导致 python curses 程序退出

c - C 中的段冲突

c - 通过calloc分配的多维数组

c++ - 如何为给定的int找到最近的偶数? (给定 11 返回 12)

C- 窗口/打印不出现

C: ncurses, initscr() 改变了 getchar() 的行为?

c - Ncurses 无输出

c - 为 FSMC LCD 编写非阻塞代码

c - 无论我要求我的系统发送什么,它只发送 FF 和 FE

terminal - 使用 Ncurses 打印双倍大小的字符