Skip to content
Tutorials Center
My learning

Topics

Lesson 132 of 135 ยท Practice and Review

Pointer Programs in C: 7 Classic Examples

Seven C pointer programs with output: functions that return pointers, jagged 2D arrays, pointer-only sorting, sorting strings, pointer palindromes, recursive list copy and stack reversal.

Pointers are easiest to understand by writing small programs that need them. This page collects seven, each built around one question that comes up again and again: Which pointers may a function safely return? How do you build a table whose rows have different lengths? Can a sort be written without a single index variable? What actually moves when you sort an array of strings? How do two pointers walking towards each other check a palindrome? How do you copy or reverse a data structure with recursion?

Every program is complete. Press Run to compile it with GCC 15 (-std=c23 -Wall -Wextra) and see the output. If pointer notation is still new, read Pointers, Pointer Arithmetic and Pointers and Arrays first.

Returning pointers

1. Three safe ways to return a pointer, and the one that is not

A function can return a pointer, but the pointer must still point at something valid when the caller uses it. There are exactly three safe sources, shown below:

  1. Into the caller's data. find_max returns a pointer to an element of the array it was given. Nothing is allocated; the caller's array outlives the call.
  2. Into heap memory. repeat allocates with malloc and returns the block. This is safe, as long as the caller knows to call free. Document that in a comment next to the function.
  3. Into static storage. day_name returns a pointer to a string literal, which lives for the whole run. This is safe too, but every call shares the same object, so a function that rebuilds a static buffer each time overwrites the previous answer.

The fourth way, in the comment, returns the address of a local variable. Locals die when the function returns, so the pointer dangles. GCC warns about it (function returns address of local variable), and reading it is undefined behavior. See Pointers and Functions and Memory Errors.

C 1. Returning pointers safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Notice max - data in the first printf. Subtracting two pointers into the same array gives the distance in elements, with the type ptrdiff_t (printed with %td).

Pointers and arrays

2. A jagged table: an array of pointers to rows

A normal 2D array has the same length in every row. When rows differ, as in Pascal's triangle where row r has r + 1 entries, an array of pointers wastes no space: int *triangle[5] holds five pointers, and each one points at a separately allocated row.

The program allocates each row with malloc((size_t)(r + 1) * sizeof **triangle). The expression sizeof **triangle is the size of one int and stays correct if the element type changes. If an allocation fails, the code frees the rows it already got before returning. The rows are filled using the rule triangle[r][c] = triangle[r-1][c-1] + triangle[r-1][c].

The print loop uses *(*(triangle + r) + c), which is exactly what triangle[r][c] means: add r to the array of pointers to find a row pointer, dereference it, add c, and dereference again. Writing it out once is a good way to see that the bracket form is only a convenient spelling of pointer arithmetic.

C 2. Jagged array with pointer arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Each row was allocated separately, so each one needs its own free, and so does the array of pointers if it was allocated with malloc (here it is a local array, so no).

3. Sorting with pointers only

Most sorting code walks arrays with indexes. This selection sort uses only pointers. sort_ints(begin, end) takes a half-open range: begin points at the first element and end points one past the last, a convention you will meet again in C++ iterators. The outer pointer i marks the next slot to fill; the inner pointer j hunts for the smallest remaining value; swap(i, smallest) puts it in place.

Pointer comparisons such as j < end are valid because both pointers point into the same array (or one past its end). Comparing pointers into different arrays is undefined behavior. The extra if (smallest != i) avoids swapping an element with itself.

C 3. Selection sort without indexes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

4. Sorting an array of strings

Which data moves when you sort strings? The answer is: only the pointers. The array const char *words[] holds five pointers, each pointing at a string literal. Bubble sort compares neighbors with strcmp and swaps the pointers; the characters of the words never move. Swapping eight-byte pointers is cheaper than swapping strings of different lengths, and it works even when the strings are read-only literals, which you could not rearrange in place.

The last line prints sizeof words: 40 bytes, five pointers of 8 bytes each, regardless of how long the words are. If you want a version with qsort, see program 36 in C Programs: 50 Classic Examples.

C 4. Sorting strings by swapping pointers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

5. Palindrome check with two pointers

The left pointer starts at the first character, and right starts at the terminator, so right - 1 is the last character. They walk toward each other. If *left is not a letter or digit, skip it; if the last character is not one, skip that; otherwise compare them case-insensitively and move both inward. When the pointers meet, everything matched.

This handles "A man, a plan, a canal: Panama" without making a cleaned-up copy of the string, and the empty string correctly counts as a palindrome. The casts to unsigned char before isalnum and tolower are required, as explained in Characters: those functions take values in the range of unsigned char or EOF, and a plain char can be negative.

C 5. Palindromes with two pointers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Pointers and recursion

6. Copying a linked list recursively

A list is either empty or a node followed by a list. That definition is already a recursive program: the copy of an empty list is the empty list, and the copy of anything else is a new node holding the same value, whose next is the copy of the rest.

C
copy->next = copy_list(head->next);

This is a deep copy: no node is shared with the original. The program proves it by changing the first value of the copy to 999 and printing both lists, then comparing the pointers. A shallow copy, such as Node *copy = original;, would have copied only the address and left the two names referring to one list.

Recursion depth equals list length, so for very long lists (hundreds of thousands of nodes) an iterative copy is safer, because each call uses stack space. See Recursion and Linked Lists.

C 6. Deep copy of a linked list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

7. Reversing a stack with recursion

Here the stack is a linked list whose head is the top, with only push and pop as operations. How can you reverse it without an array or a second stack? Use the call stack as scratch space, in two small recursive functions.

  • insert_at_bottom(top, x) pops everything off, pushes x onto the now-empty stack, and then pushes everything back on top of it, in the original order. Each element is held in a local variable held while the recursion below it works.
  • reverse(top) pops the top element, reverses the rest recursively, and then slides the popped element in at the bottom.

Both use a pointer to the pointer to the top (Item **top) so that push and pop can change the caller's head, the same technique as in Pointers to Pointers. The price is time: this reversal is O(nยฒ), because every reverse step runs a full insert_at_bottom. Real code would just pop into a second stack. The exercise is worth doing because it shows how recursion turns local variables into a hidden stack of their own.

C 7. Reversing a stack using recursion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these pointers is safe to return from a function?

    The caller's array is still alive after the function returns. Locals and by-value parameters are destroyed on return, so pointers to them dangle.
  2. 2. In the jagged-array program, why does each row need its own free call?

    Every successful malloc returns a block that must be freed exactly once. Five rows came from five calls, so there are five frees.
  3. 3. When an array of strings (const char *words[]) is sorted, what is moved?

    Each element is a pointer to a string. Swapping two elements swaps two addresses, so the characters stay where they are.
  4. 4. What does it mean that copy_list makes a deep copy?

    A deep copy shares no nodes with the original. Changing or freeing one list does not affect the other. Recursion is how this particular program builds it, not what defines it.
  5. 5. Why is the recursive stack reversal O(n squared)?

    reverse runs once per element and each run calls insert_at_bottom, which pops and re-pushes up to n elements. That gives about n times n steps.

Summary

  • A returned pointer must still be valid after the function ends: into the caller's data, into heap memory the caller frees, or into static storage. Never return the address of a local.
  • An array of pointers builds tables with rows of different length; p[r][c] is *(*(p + r) + c).
  • Pointer-only loops use a half-open range [begin, end); compare and subtract only pointers into the same array.
  • Sorting strings swaps pointers, not characters.
  • Two pointers moving toward each other solve palindrome-style checks without copying.
  • Recursive definitions of lists ("empty, or a node and a list") become short recursive functions. A pointer to the head pointer lets a helper change what the caller's head points to.

Next: Unusual C Programs, where you will write a program that prints itself and learn to tell the four kinds of errors apart.