Page 1 of 1

Function to get a character at the current cursor position

Posted: Sun Dec 19, 2021 11:14 am
by Caffeine
Hi, I'm trying to make a function to get a character at a cursor position. So far, I have:

Code: Select all

char getCharacterAtCursor() {

    unsigned short *index;
    index = &videoMemory + ((cursorY * 80) + cursorX);
    return *index;
}
Thanks!

Re: Function to get a character at the current cursor positi

Posted: Sun Dec 19, 2021 11:37 am
by vhaudiquet
What is 'videoMemory' ? I don't understand why you are using &videoMemory...
Be careful when computing addresses inside of pointers, and go back to computing the address as a void* / integer directly if you have a doubt.
Anyway, in the end you will want an uint8_t/char pointer so doing the calculations in an uint16_t pointer is not really necessary.
This should work : (VGA_MEM_ADDR is vga mem start address, e.g. 0xB8000, and VGA_COLUMNS is 80 ; addr_t is uint32_t or uint64_t depending on architecture)

Code: Select all

char getCharacterAtCursor()
{
    addr_t address = VGA_MEM_ADDR + (cursorY * VGA_COLUMNS * 2) + (cursorX * 2);
    return *((char*) address);
}

Re: Function to get a character at the current cursor positi

Posted: Sun Dec 19, 2021 11:55 pm
by nullplan

Code: Select all

char getCharacterAtCursor(void) {
  struct {
    uint8_t character;
    uint8_t attribute;
  } (*screen)[height][width] = (void*)videoMem;
  return (*screen)[cursorY][cursorX].character;
}
With constant width and height, this works with C89, and with variable width and height this requires C99. You are writing in a high-level language, you don't have to write assembler. In this case, the compiler is able and willing to do the address calculation for you.