```
Back to list
Programowanie strukturalne

Programowanie Strukturalne

CDV #programowanie #programowanieC

Why do we use pointers in C?

A pointer is also stored in memory like any other variable. The difference is that a normal variable stores a value, while a pointer stores the address of another place in memory.

Chart 1: value and pointer in memory

Here, value is stored at address 42 and contains 98765. The pointer ptr is stored at address 68 and contains 42, so it points to value.

Memory Both variables are stored inside memory. 10 11 12 13 14 15 16 17 18 19 20 40 41 42 98765 43 44 45 46 47 68 42 69 70 int value int *ptr

Chart 2: pointer to an array with 15 elements

The array occupies many memory cells. The pointer is still just one separate variable. It stores only the address of the first array element.

Memory Both the array and the pointer are stored inside the same memory. 30 10001 31 10002 32 10003 33 10004 34 10005 35 10006 36 10007 37 10008 38 10009 39 10010 40 99990 41 43210 42 54321 43 67890 44 11111 45 22222 46 33333 47 44444 48 55555 49 66666 50 77777 51 88888 52 99999 53 13579 54 24680 55 86420 68 30 69 31415 70 27182 71 16180 int arr[15] int *p arr[0]

Example 1: copying a large array vs passing a pointer

In C, arrays are usually passed as pointers. To clearly demonstrate the cost of copying, we wrap the array inside a structure. Passing the structure by value copies the whole array, while passing a pointer only sends its memory address.

#include <stdio.h>

#define SIZE 1000000

typedef struct {
    int data[SIZE];
} BigArray;

// Full copy of the whole structure
long long sum_by_copy(BigArray arr) {
    long long sum = 0;
    for (int i = 0; i < SIZE; i++) {
        sum += arr.data[i];
    }
    return sum;
}

// Only the address is passed
long long sum_by_pointer(const BigArray *arr) {
    long long sum = 0;
    for (int i = 0; i < SIZE; i++) {
        sum += arr->data[i];
    }
    return sum;
}

int main() {
    BigArray arr;
    for (int i = 0; i < SIZE; i++) {
        arr.data[i] = 1;
    }

    printf("sum_by_copy    = %lld\n", sum_by_copy(arr));
    printf("sum_by_pointer = %lld\n", sum_by_pointer(&arr));

    return 0;
}

The first function receives a complete copy of the large array, which is expensive. The second function receives only a pointer, so it can read the same data without duplicating it.

Example 2: modifying the original array through a pointer

Pointers also let functions directly modify the original data. This avoids copying and allows multiple parts of a program to work on the same array.

#include <stdio.h>

#define SIZE 5

void fill_with_zero(int *arr, int size) {
    for (int i = 0; i < size; i++) {
        arr[i] = 0;
    }
}

int main() {
    int big_array[SIZE] = {10, 20, 30, 40, 50};

    fill_with_zero(big_array, SIZE);

    for (int i = 0; i < SIZE; i++) {
        printf("%d ", big_array[i]);
    }
    printf("\n");

    return 0;
}
— Jacek Kałużny
```