Learn to Code via Tutorials on Repl.it!

← Back to all posts
C wars: Chapter Five: The empire points back
CodeLongAndPros (1644)

Chapter five: The Empire points back

Today, we will be talking about one of the most loved/feared C features.

That's right: pointers (As defined in K&R)

Please make a new C repl and add the bones:

First, let's talk about how C uses memory.

Think about 3 cubbies next to each other:

These are at addresses: 0, 1, and 2

A pointer is a piece of data, in a cubby, in this case, 0, that points -> to another cubby (1)

To get the cubby of a bit of data (No pun intended), use &.

So add this to main:

You should have this:

The number in {} is the address of a.

You can dereference a pointer using *.

Add this to main:

Main should now == this:

If, at line 8, you add int y = *ap; and at line 10/11 you add printf("%d\n", ++y);/printf("%d\n", a);, you can see that y has the value of a;

We will also discuss using pointers in functions in Chapter Six: Return of the function.

Now, for another pointer-related topic:


You define a array using the syntax:
type name[size]
An array is one var that has x of each type in it

So int a[2] is a two long array.

You access the elements in a array using arr[index]. (Note: starts from zero)

So a[0] gets the first element of an array

If you make a pointer to &a[0], and deref it to x, x has the value of a[0] but if you add one to &a[0], it points to a[1]: *(p+1)

Since a string is a char array, int* str = &s and *(str + 1) refer to the first and second chars. It is also perfectly valid to do ++ on a pointer to refer to p + 1


Make a program, strlen, that takes a string as input and ouputs the length.

You will need a for loop, a pointer to the string, and use of ++


Part One: The Segfault menace

Part Two: The data wars

Part Three: Revenge of the if

Part Four: A new loop

Part Five: The Empire points back

Part Six: Return of the function

HahaYes (1868)

If I upvote, you become #1 in the tutorial section. Hmmmm I want this to reach out to more people so why not.

HahaYes (1868)

Yayyyy a new tutorial yayyyy

Highwayman (1537)

For some reason the title just really got me XD

CodeLongAndPros (1644)

Just BTW, should I do the next chapter today since the two are closely related?

HahaYes (1868)

also you have the same amount of cycles as me!

HahaYes (1868)

hmmm when are you going to run out of star wars puns

Jakman (453)

Thank you. May god smile upon you for this tutorial.