Learn to Code via Tutorials on Repl.it

← Back to all posts
Random Stuff with Pointers (in C++)!
DynamicSquid (103)

What's a pointer?

This isn't meant to be a pointer tutorial, but just a quick recap:

Pointers store memory addresses!

What if they don't?

But what happens if you don't initialize a pointer? Does it point to nothing? Let's find out!


int* pointer1;
int* pointer2 = NULL;

if (pointer1) // evaluates to true if pointer is not NULL
  std::cout << "Pointer1 contains random memory address";
if (pointer2)
  std::cout << "Pointer2 contains no address";


Pointer1 contains random memory address


As you can see, if you don't initialize a pointer, then it doesn't contain nothing, but instead a random address!

So always initialize your pointers!

Highwayman (1084)

Or you could use pointer intializations to make a really janky rng ;)

uint64_t janky_rng(){
  void *x;
  return (uint64_t)x;
DynamicSquid (103)

@Highwayman Oh that's interesting, I never thought of that! But doesn't the result get treated like a memory address instead of an integer?

Highwayman (1084)

@DynamicSquid it is a memory address, let me revise it a little for you...

Highwayman (1084)

@Highwayman there. It is, but I just cast it to a normal unsigned integer that’s 8 bytes long, so now it’s just a number.

CSharpIsGud (222)

Do remember that doing if (pointer) will be true if the pointer is a valid pointer. if the data at the pointers address is null but the pointer points to a valid location in memory it will be "true".
NULL is usually (void*) 0(This is not guaranteed everywhere, the only thing that is guaranteed is that it is an invalid pointer) and obviously 0 is not a valid memory address.