0.1 Pointers

Pointers have its reputation of being hard to understand when it is just another data type. I was planning to not create a separate section for pointer and just put it in the previous section alongside other data types, but I wanted to discuss more about arrays and strings that we missed earlier and discuss about dynamic memory allocation. So in this section we are going to not only discuss about pointers, but also related topics.

So pointers in short is just a variable that stores the address of another variables. So what does this mean? When we store a value like int a = 5, computers have to store that information somewhere. Integers like these are usually 4 bytes and written in binaries. Computers store this information in memory, or better known as RAM (Random Access Memory). When storing the information, they don’t just store it, but allocates a space, or address, in the memory for the value. Here is an example.

Memory Address Value
0x16bc6ac18 5
0x16bc6ac10 0.100000
0x16f7a2c0f A

Pointer is just a variable that stores that memory address of an object. Here is the snippet that declares and prints pointer values.

Code 0.1.1: 26sbpfz-01

1#include <stdio.h> 
2 
3int main() { 
4    int a = 5; 
5    double b = 0.1; 
6    char c = ’A’; 
7 
8    int* pA = &a; 
9    double* pB = &b; 
10    char* pC = &c; 
11 
12    printf("%d, %p\n", a, pA); 
13    printf("%f, %p\n", b, pB); 
14    printf("%c, %p\n", c, pC); 
15 
16    return 0; 
17}

Output 0.1.2

5, 0x16bc6ac18 
0.100000, 0x16bc6ac10 
A, 0x16f7a2c0f

Here I used int* pA, but int * pA and int *pA does the same thing. Also it is a convention to have “p” in front of a pointer variable!

Being able to directly manipulate how the program manages memory is great because we can efficiently manage memory with manual allocation, pass data more efficiently by pointing instead of having a copy of the variable, and build data structures like trees and linked lists.

We can access the variable with its memory address, or pointer, and change it. This gives us freedom on how we use memory in our program. But this freedom is also what makes it easy for us to shoot ourselves in the foot. But before getting to much into that, let’s take a look at how we can dereferece a pointer to change the value that it is pointing at.

Code 0.1.3: 26sbpfz-02

1#include <stdio.h> 
2 
3int main() { 
4    int num = 5; 
5    printf("Original num: %d\n", num); 
6 
7    int* pNum = &num; 
8    *pNum = 10; 
9    printf("New num: %d\n", num); 
10 
11    return 0; 
12}

Output 0.1.4

Original num: 5 
New num: 10

As you can see, I like to see it as negative times negative is positive. We give one more asterisk to let the compiler know that we are dereferencing a referenced value. With this, I think it is now evident why we need & when using scanf! We are basically passing pointers to indirectly change the value of the declared variable. Let’s take a deeper look at how arrays and strings work with pointers.

A string is literally an array of character. So if we define char str[] = "Hello", it will create an array like {’H’, ’e’, ’l’, ’l’, ’o’, ’\0’} where \0 is a null character that terminates the string. For that reason, when we use pointer with a string, it will work index by index. Here is what I mean.

Code 0.1.5: 26sbpfz-03

1#include <stdio.h> 
2 
3int main() { 
4    char str[] = "Hello"; 
5    char* ptr = str; 
6 
7    *ptr = ’A’; 
8    printf("%s\n", str); 
9 
10    *(ptr + 2) = ’A’; 
11    printf("%s\n", str); 
12 
13    return 0; 
14}

Output 0.1.6

Aello 
AeAlo

As you can see, when we initialize the pointer for the string, the pointer is actually pointing to the address of the first character. The pointer can’t store the address of the string because the string has many addresses. When we want to access diffferent element in the string, we can use arithmetic to find the right index. Also, if you wondered why we don’t put ampersand for string when declaring a pointer and using scanf, that is because the pointer is automatically assigned to the first character.

Now as we can see from char name[20] example, we can manually allocate memory in C. This causes a problem when we don’t do it properly. Sometimes if we don’t release memory after we no longer needed, the program will not only degrade performance but also could crash due to memory leaks. To avoid it, we need to free memory after allocating it. Here is an example.

Code 0.1.7: 26sbpfz-04

1#include <stdio.h> 
2#include <stdlib.h> 
3 
4int main() { 
5    int* num = malloc(5 * sizeof(int)); 
6 
7    for (int i = 0; i < 5; i++) { 
8        num[i] = i; 
9    } 
10    for (int i = 0; i < 5; i++) { 
11        printf("%d ", num[i]); 
12    } 
13    printf("\n"); 
14 
15    free(num); 
16 
17    return 0; 
18}

Output 0.1.8

0 1 2 3 4

Without free(num);, we will have memory leaks and cause degradation of the program. Continuing from the strings, you may have seen lots of arrows in C programs. Those are actually pointers as well! Here is an example of using pointers with structs.

Code 0.1.9: 26sbpfz-05

1#include <stdio.h> 
2 
3typedef struct { 
4    int a; 
5    int b; 
6    int c; 
7} array; 
8 
9int main() { 
10    array arr = { 1, 2, 3 }; 
11    array* parr = &arr; 
12    printf("Original Array: [%d, %d, %d]\n", arr.a, arr.b, arr.c); 
13 
14    (*parr).a = 4; 
15    parr->b = 5; 
16    parr->c = 6; 
17    printf("New Array: [%d, %d, %d]\n", arr.a, arr.b, arr.c); 
18 
19    return 0; 
20}

Output 0.1.10

Original Array: [1, 2, 3] 
New Array: [4, 5, 6]

Finally before wrapping up this section, we can also now write and modify files with C using pointers!

Code 0.1.11: 26sbpfz-06

1#include <stdio.h> 
2 
3int main() { 
4    FILE* fptr = fopen("file.txt", "w"); // r, w, a 
5    fprintf(fptr, "Hello World\n"); 
6    fclose(fptr); 
7 
8    return 0; 
9}

Running this, we should get a file “file.txt” in the directory where the program was ran with the text “Hello World” in it. This is it for pointers! Before we write exciting programs, we will be going over header guard and macro in the next section.