Home > Blockchain >  How can I access a CHAR_INFO structure from within a function
How can I access a CHAR_INFO structure from within a function

Time:10-16

I have some very basic code that is using the Windows API to display random characters and colours to the console by accessing the console buffer directly.

My problem is that I want to put the nested for loop into a separate function outside the main() function. Ideally this function would take the struct consoleBuffer as an argument/parameter but I dont know how the sintax for a CHAR_INFO struct works well enough. The other option is declaring consoleBuffer as a global outside the main function so that it can be accesed anywhere and we dont have to set it as a parameter but this does not work.

code:

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

#define WIDTH 70
#define HEIGHT 35

HANDLE wHnd; //Write Handle

int main(void)
{
 int x, y;
  
 SMALL_RECT windowSize = {0, 0, WIDTH - 2, HEIGHT - 2};

 // screen buffer size
 COORD bufferSize = {WIDTH, HEIGHT};
  
 // Variables for WriteConsoleOutput
 COORD characterBufferSize = {WIDTH, HEIGHT};
 COORD characterPosition = {0, 0};
 SMALL_RECT consoleWriteArea = {0, 0, WIDTH - 1, HEIGHT - 1};
  
 // A CHAR_INFO structure containing data about a single character
 CHAR_INFO consoleBuffer[WIDTH * HEIGHT];
 
 wHnd = GetStdHandle(STD_OUTPUT_HANDLE);
 
 // Console title
 SetConsoleTitle("CONSOLE");
 
 //Set window
 SetConsoleWindowInfo(wHnd, TRUE, &windowSize);

 //Buffer size
 SetConsoleScreenBufferSize(wHnd, bufferSize);
  
 while(1){
  for (y = 0; y < HEIGHT;   y){
   for (x = 0; x < WIDTH;   x){
    consoleBuffer[x   WIDTH * y].Char.AsciiChar = 'a';
    consoleBuffer[x   WIDTH * y].Attributes = rand() % 256;
   }
  }
  
  //Write characters
  WriteConsoleOutputA(wHnd, consoleBuffer, characterBufferSize, characterPosition, &consoleWriteArea);
 }
}

CodePudding user response:

Essentially the problem is that you need to set pointer to the CHAR_INFO struct if you want it as an argument. An example of the funcion could be the following:

void foo(CHAR_INFO* cB){
    int x,y;
    for (y = 0; y < HEIGHT;   y){
   for (x = 0; x < WIDTH;   x){
    cB[x   WIDTH * y].Char.AsciiChar = 'a';
    cB[x   WIDTH * y].Attributes = rand() % 256;
   }
  }
}
  • Related