← The C Language Lesson 24 of 77 · 10 XP

Pointers

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A pointer is a variable that holds an address:

int x = 10;
int *p = &x;      // p points to x
printf("%d\n", *p);   // 10 — * "dereferences": takes the value at the address
*p = 20;          // change x through the pointer
printf("%d\n", x);    // 20

* in a declaration (int *p) means "this is a pointer". In an expression (*p) it means "the value at the address".

Pointer arithmetic: p + 1 points to the next item, not the next byte.

int a[] = {10, 20, 30};
int *p = a;            // = &a[0]
printf("%d\n", *(p + 2));   // 30
// a[i] is by definition *(a + i)

The special value NULL means "points to nothing". Dereferencing NULL is an error; the program crashes.

A pointer that looks into memory that has already been freed or belongs to someone else is a dangling pointer. It's one of the main sources of bugs in C.

Task. Read n (up to 100) and n numbers into an array. Find the sum of the items by going through the array with a pointer (for (int *p = a; p < a + n; p++)), without indices.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.