- Compiler:gcc 4.5.2
- Terminal:Xterm
- OS:Linux(x86)
- Ncurses 5.9
I am programming a text editor that uses ncurses to graphicaly represent an array key_strokes[]. It is one dimensional so I use the macro INDEX(y*maxx+x) to point to the current position in key_strokes (key_strokes[INDEX]). y and x are the current coordinates in the terminal returned by the function getyx(stdscr, y, x) and maxx is the max amount of cols that can be in each row returned by the function getmaxyx(stdscr, maxy, maxx). The program works great until I press backspace, for some reason the value of maxx is set to zero after it reaches the switch below. This of course throws off INDEX limiting it to only the first “row” of the array.
The user’s key strokes are captured as int key_strokes. I use a switch case to check and see if it is an arrowkey, backspace, F12, etc. INDEX and maxx are defined as,
#define INDEX (y*maxx+x)
unsigned int maxx = 0;
Note I am also using 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;
Are you sure that
key_strokes[]is null terminated?’cause if it isn’t, the
forloop will copy everything in memory to the previous cell, until it reaches 0. And ifmaxxormaxyare right before a 0 value, they will be set to 0.Imagine the following layout:
After pressing backsapce after ‘i’, it will be:
That could also explain why it’s
maxywhich is set to 0 whenmaxxis declared const (GCC doesn’t store theconsts at at the same place in memory).To ensure that
key_strokes[]is null-terminated, I’d suggest you to add this into your init section: