Function to get a character at the current cursor position

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
Caffeine
Member
Member
Posts: 79
Joined: Mon Nov 15, 2021 9:48 pm

Function to get a character at the current cursor position

Post 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!
vhaudiquet
Member
Member
Posts: 43
Joined: Sun Aug 20, 2017 10:59 am

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

Post 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);
}
nullplan
Member
Member
Posts: 1790
Joined: Wed Aug 30, 2017 8:24 am

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

Post 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.
Carpe diem!
Post Reply