C.

The most influential programming language that has ever existed.

It powers supercomputers, embedded systems, and every popular software tool you use today.

Learning C will help you unlock a new power that you will never possess by writing Python and JavaScript:

Memory management.

Variable & Virtual Memory

To get started, create a main function and an integer i with a value of 0.

When your program runs, that variable needs to be stored somewhere.

Where is it?

The RAM.

(technically, not the physical RAM but a virtual RAM)

Let’s zoom in a little bit.

Variable i lives in 0×1000.

Notice there’s a 0x in front?

Memory addresses are written in hexadecimal.

Its decimal version looks like this:

The size of an integer is 4 bytes.

So, if you create another variable j.

Its memory address is 1004, instead of 1001.

Pointers

Now let’s talk about a special type of variable called pointers.

A regular variable stores an integer, a character, etc.

A pointer stores a memory address.

Here's how it works.

First, get the memory address of a variable, like i, with the & operator:

&i; //0x1000

Assign that value to a new variable called i_ptr.

int* i_ptr = &i;

Notice how there’s an asterisk (*) in front?

We need that to create a pointer instead of an integer.

Let’s see what happens in the RAM.

A new variable i_ptr is created.

The only thing special is that its value is a memory address of another variable.

Now you can read and write the value of that variable (int i) through the pointer.

This is how you read it:

*i_ptr; //0

And this is how you overwrite it:

*i_ptr = 4;

The value of i should become 4.

Let's test it by printing it out.

int main() {
  int i = 0;
  int *i_ptr = &i;

  *i_ptr = 4;

  printf("value of i: %d\n", i);
}

To run the code, install a C compiler, like gcc.

Compile the code into machine code.

Then run the executable file.

You will see the value of i becomes 4.

value of i: 4

And you have just learnt the fundamentals of pointers & memory management in C.

Fee from Anime Coders

How did you like today's email?

Login or Subscribe to participate

Keep Reading