PeekInt, PokeInt, Peek, Poke equivalent in C from BASIC

I was wondering what is the equivalent of the command Peek and Poke (Basic and other variants) in C. Something like PeekInt, PokeInt (integer).

Something that deals with memory banks, I know in C there are lots of ways to do this and I am trying to port a Basic program to C.

Is this just using pointers? Do I have to use malloc?


  • Yes, you will have to use pointers. No, it does not necessarily involve malloc.

    If you have a memory address ADDRESS and you want to poke a byte value into it, in C that's

    char *bytepointer = ADDRESS;
    *bytepointer = bytevalue;

    As a concrete example, to poke the byte value 0h12 to memory address 0h3456, that would look like

    char *bytepointer = 0x3456;
    *bytepointer = 0x12;

    If on the other hand you want to poke in an int value, that looks like

    int *intpointer = ADDRESS;
    *intpointer = intvalue;

    "Peeking" is similar:

    char fetched_byte_value = *bytepointer;
    int fetched_int_value = *intpointer;

    What's happening here is basically that these pointer variables like bytepointer and intpointer contain memory addresses, and the * operator accesses the value that the pointer variable points to. And this "access" can be either for the purpose of fetching (aka "peeking"), or storing ("poking").

    See also question 19.25 in the C FAQ list.

    Now, with that said, I have two cautions for you:

    1. Pointers are an important but rather deep concept in C, and they can be tricky to understand at first. If you've never used a pointer, if you haven't gotten to the Pointers chapter in a good C textbook, the superficial introduction I've given you here isn't going to be enough, and there are all sorts of pitfalls waiting for you if you don't learn about them first.

    2. Setting a pointer to point to an absolute, numeric memory address, and then accessing that location, is a low-level, high-powered technique that ends up being rather rare these days. It's useful (and still commonly used) if you're doing embedded programming, if you're using a microcontroller to access some hardware, or perhaps if you're writing an operating system. In more ordinary, "applications" level programming, on the other hand, there just aren't any memory addresses which you're allowed to access in this way.

    What values do you want to peek or poke, to accomplish what? What is that Basic program supposed to do? If you're trying to, for example, poke values into display memory so they show up on the screen, beware that on a modern operating system (that is, anything newer than MS-DOS), it doesn't work that way any more.