Search code examples
carrayssizeconstantsncurses

Not able to use LINES and COLS as constants in ncurses


Greetings all—first time poster here. I'm building a program in C using ncurses where I need to declare a two-dimensional array that is the height and width of the user's terminal screen, which will of course vary from user to user (we will assume that it will stay constant while running the program). Much of the documentation out there tells me that Ncurses provides LINES and COLS as constants that are equal to my screen size, but I get a compile error when I try to use these "constants" to declare the size of my array ("variable-sized object may not be initialized").

I am familiar with the getmaxyx function, and it returns the same dimensions as LINES and COLS for a window that is the size of the terminal screen. So the math adds up fine.

How can I use the size of the user's screen as the dimensions of a two-dimensional array?


Solution

  • Your only issue is what the error message says: that a "variable-sized object may not be initialized".

    In other words, you are writing something like:

    int main(void) {
      int screen[LINES][COLS] = {{0}};
    

    Instead of:

    int main(void) {
      int screen[LINES][COLS];
      for (int r = 0; r < LINES; ++r)
        for (int c = 0; c <  COLS; ++c)
          screen[r][c] = 0;
    

    LINES and COLS are not constants, they are variables. (Unless you're running an OS without a windowing system, it's also very optimistic to assume they won't change during a session. They will change if the user resizes their console window. If you don't respond appropriately to the resize, your app is going to be problematic.)

    Even if they don't change during the execution of the program, their values are not known to the compiler, which prevents it from initialisation (according to the C standard). So it insists you initialise the array by hand, if you want it to be initialised.

    But there is no problem with declaring it.

    Note: As Thomas Dickey points out in a comment, variable-length arrays (VLAs) (like your screen) are not universally implemented, since C11 made the feature optional. If you encounter this problem, the most likely cause is that you are using Microsoft's C compiler, which is the most widely used modern compiler which doesn't support VLAs. In that case, you'll either have to rewrite the code to do your own computation of array subscripts, or use a different compiler.