Pointer Arithmetic Examples in Embedded C: Strings, Checksums, Ring Buffers, Matrices and Filters-Free Embedded C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

MODULE 9 · LESSON 9.2 · EXAMPLES

Pointer Arithmetic Examples in Embedded C: Strings, Checksums, Ring Buffers, Matrices and Filters

Eight worked examples with real output: strlen and strcpy, byte and word checksums, two-pointer reversal, a ring buffer, matrix row pointers, overlapping copies, a number-list parser and a sliding-window average. Study this one of the pointer arithmetic examples in embedded C closely.

9
Worked Examples
Intermediate
Level
Real output
Compiled and run

Pointer Arithmetic Examples in Embedded C: What This Page Covers

These pointer arithmetic examples in embedded C apply Lesson 9.2: string routines written with pointers, byte and word checksums, in-place reversal with two pointers, a ring buffer with head and tail pointers, matrix rows, overlapping copies, a number-list parser and a sliding-window average. Every program was compiled with GCC and run; the output is real. These pointer arithmetic examples in embedded C build on each other.

#ExampleSkill
1strlen and strcpy with pointers*p++
2Checksums over bytes and wordsStep size
3Reverse and palindrome with two pointersConverging pointers
4A ring buffer with head and tail pointersWrap-around
5Matrix row sums with row pointers2D arrays
6Overlapping copies: forward or backward?memmove logic
7Parsing a number list with a cursorPointer advance
8Sliding-window averagePointer difference
9Mini exercisesSelf-test

Example 1: strlen and strcpy with Pointers

Problem: Re-implement two standard string functions with pointer arithmetic. my_strlen advances a copy of the pointer until it finds the zero byte; the difference p - s is the length. my_strcpy uses the classic *d++ = *src++ loop: the assignment expression has the value that was copied, so the loop stops after the terminator has been written. The destination must be large enough (here 16 bytes for 10 including the terminator); the function cannot check it, which is why size-limited versions exist (Lesson 8.2). Among the pointer arithmetic examples in embedded C this pattern is very common.

strfuncs.c
#include <stdio.h> #include <stddef.h> static size_t my_strlen(const char *s) { const char *p = s; while (*p) p++; /* stop at the terminating zero */ return (size_t)(p – s); /* distance = number of characters */ } static char *my_strcpy(char *dst, const char *src) { char *d = dst; while ((*d++ = *src++) != ‘\0’) /* copy including the terminator */ ; return dst; } int main(void) { const char *msg = “STM32F407”; char copy[16]; printf(“length of \”%s\” = %zu\n”, msg, my_strlen(msg)); my_strcpy(copy, msg); printf(“copy = \”%s\”, length %zu\n”, copy, my_strlen(copy)); printf(“empty string length = %zu\n”, my_strlen(“”)); return 0; }
Output (verified by compiling and running)
length of “STM32F407” = 9 copy = “STM32F407”, length 9 empty string length = 0
Real code: Prefer the library versions or size-aware variants such as strncpy/snprintf with careful termination. The loops above show how they work, not how to write a production API.

Example 2: Checksums over Bytes and Words

Problem: Compute simple checksums for a frame and for a table in Flash. The byte versions step one byte at a time; sum32_words takes a uint32_t *, so *p++ moves four bytes per step and the count is in words. The loop idiom while (n--) runs exactly n times. Sums of unsigned values wrap around by definition: 0x100 + 0x200 + 0xFFFFFFFF + 2 = 0x301 modulo 232. The 8-bit sum of 01+02+03+F0+0F is 0x105, which truncates to 0x05, while the xor of the same bytes is 0xFF: different checksums give different values for the same data. The last line reads the same table as 16 bytes through a byte pointer. Keep these pointer arithmetic examples in embedded C for revision.

checksums.c
#include <stdio.h> #include <stdint.h> #include <stddef.h> static uint8_t sum8(const uint8_t *p, size_t n) { uint8_t s = 0; while (n–) s = (uint8_t)(s + *p++); return s; } static uint8_t xor8(const uint8_t *p, size_t n) { uint8_t x = 0; while (n–) x ^= *p++; return x; } static uint32_t sum32_words(const uint32_t *p, size_t words) /* steps 4 bytes at a time */ { uint32_t s = 0; while (words–) s += *p++; return s; } int main(void) { uint8_t msg[] = { 0x01, 0x02, 0x03, 0xF0, 0x0F }; printf(“sum8 = 0x%02X, xor8 = 0x%02X\n”, sum8(msg, sizeof msg), xor8(msg, sizeof msg)); uint32_t table[] = { 0x00000100u, 0x00000200u, 0xFFFFFFFFu, 0x00000002u }; printf(“sum32 = 0x%08X (wraps modulo 2^32)\n”, (unsigned)sum32_words(table, sizeof table / sizeof table[0])); /* same table seen as bytes: 16 bytes instead of 4 words */ printf(“sum8 of the table’s 16 bytes = 0x%02X\n”, sum8((const uint8_t *)table, sizeof table)); return 0; }
Output (verified by compiling and running)
sum8 = 0x05, xor8 = 0xFF sum32 = 0x00000301 (wraps modulo 2^32) sum8 of the table’s 16 bytes = 0x01
Where it is used: A bootloader sums the application image words and compares the result with a stored value before jumping to it (Lesson 8.4). Word loops are faster than byte loops on a 32-bit core, provided the data is word-aligned.

Example 3: Reverse and Palindrome with Two Pointers

Problem: Process an array from both ends. Two pointers start at the first and last element and move towards each other; the loop condition lo < hi compares them (same array, so the comparison is valid) and stops when they meet or cross, which works for even and odd lengths without special cases. *lo++ = *hi and *hi-- combine the access and the step. The same pattern appears in reversing byte order of a buffer and in checking symmetric patterns.

two_ptr.c
#include <stdio.h> #include <stddef.h> #include <string.h> static void reverse(char *s, size_t n) { char *lo = s, *hi = s + n – 1; while (lo < hi) { char t = *lo; *lo++ = *hi; *hi– = t; /* swap and move inwards */ } } static int is_palindrome(const char *s, size_t n) { const char *lo = s, *hi = s + n – 1; while (lo < hi) if (*lo++ != *hi–) return 0; return 1; } int main(void) { char word[] = “firmware”; reverse(word, strlen(word)); printf(“reversed: %s\n”, word); const char *tests[] = { “level”, “radar”, “uart”, “a”, “abba” }; for (int i = 0; i < 5; i++) printf(“%-6s palindrome? %s\n”, tests[i], is_palindrome(tests[i], strlen(tests[i])) ? “yes” : “no”); return 0; }
Output (verified by compiling and running)
reversed: erawmrif level palindrome? yes radar palindrome? yes uart palindrome? no a palindrome? yes abba palindrome? yes
Careful: For n == 0 the expression s + n - 1 points before the array, which is undefined. Guard empty input before calling, or use an index loop.

Example 4: A Ring Buffer with Head and Tail Pointers

Problem: Buffer UART bytes between an interrupt and the main loop. The producer writes at head, the consumer reads at tail; each pointer wraps to the start when it reaches buf + CAP. A separate counter distinguishes full from empty (when head equals tail the buffer could be either). The fifth push is rejected because the buffer holds four bytes; after two pops the pushes of 6 and 7 wrap around to the beginning of the array. Draining returns the data in first-in first-out order: 3, 4, 6, 7.

ring_ptr.c
#include <stdio.h> #include <stdint.h> #define CAP 4 static uint8_t buf[CAP]; static uint8_t *head = buf, *tail = buf; /* head: write, tail: read */ static unsigned used; static int rb_push(uint8_t v) { if (used == CAP) return –1; /* full */ *head++ = v; if (head == buf + CAP) head = buf; used++; return 0; } static int rb_pop(uint8_t *v) { if (used == 0) return –1; /* empty */ *v = *tail++; if (tail == buf + CAP) tail = buf; used–; return 0; } int main(void) { for (uint8_t i = 1; i <= 5; i++) printf(“push %u -> %d\n”, i, rb_push(i)); /* the fifth push fails */ uint8_t v; rb_pop(&v); printf(“pop -> %u\n”, v); rb_pop(&v); printf(“pop -> %u\n”, v); int r6 = rb_push(6); /* wraps around */ int r7 = rb_push(7); printf(“push 6 -> %d, push 7 -> %d\n”, r6, r7); printf(“tail index %td, head index %td, used %u\n”, tail – buf, head – buf, used); printf(“draining:”); while (rb_pop(&v) == 0) printf(” %u”, v); printf(“\nempty pop -> %d\n”, rb_pop(&v)); return 0; }
Output (verified by compiling and running)
push 1 -> 0 push 2 -> 0 push 3 -> 0 push 4 -> 0 push 5 -> -1 pop -> 1 pop -> 2 push 6 -> 0, push 7 -> 0 tail index 2, head index 2, used 4 draining: 3 4 6 7 empty pop -> -1
Concurrency: This version is single-context. When an ISR pushes and main pops, the shared state (used, the pointers) must be handled with volatile and atomic updates, or by using indices owned by one side each (Module 14).

Example 5: Matrix Row Sums with Row Pointers

Problem: Sum the rows and columns of a small matrix, such as a 3 × 4 block of sensor readings. The parameter int (*m)[COLS] is a pointer to a row of four ints, so m[r] is the row and m[r][c] the element; the column count is part of the type, which lets the compiler scale the row step. Inside row_sums a plain int * walks one row. The explicit cast in main adds const to the row type: strictly, ISO C up to C17 does not allow the implicit conversion from int (*)[4] to const int (*)[4], and GCC reports it with -pedantic, so the cast keeps the code portable. Sizes confirm the layout: 12 ints = 48 bytes, one row = 16 bytes.

rows_ptr.c
#include <stdio.h> #define ROWS 3 #define COLS 4 static void row_sums(int (*m)[COLS], int rows, int *out) { for (int r = 0; r < rows; r++) { int *p = m[r]; /* pointer to the first element of row r */ int s = 0; for (int c = 0; c < COLS; c++) s += *p++; out[r] = s; } } static void col_sums(const int (*m)[COLS], int rows, int *out) { for (int c = 0; c < COLS; c++) { out[c] = 0; for (int r = 0; r < rows; r++) out[c] += m[r][c]; } } int main(void) { int m[ROWS][COLS] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; int rs[ROWS], cs[COLS]; row_sums(m, ROWS, rs); col_sums((const int (*)[COLS])m, ROWS, cs); printf(“row sums :”); for (int r = 0; r < ROWS; r++) printf(” %d”, rs[r]); printf(“\n”); printf(“column sums:”); for (int c = 0; c < COLS; c++) printf(” %d”, cs[c]); printf(“\n”); printf(“sizeof(m) = %zu bytes, one row = %zu bytes\n”, sizeof m, sizeof m[0]); return 0; }
Output (verified by compiling and running)
row sums : 10 26 42 column sums: 15 18 21 24 sizeof(m) = 48 bytes, one row = 16 bytes

Example 6: Overlapping Copies, Forward or Backward?

Problem: Shift part of a buffer inside itself (inserting bytes in a message, scrolling a display line). If the destination lies above the source and the areas overlap, a forward copy overwrites source bytes before they are read; the loop must run backward. The program shifts “ABCDE” two places to the right: the correct result is ABABCDEHI, while the naive forward loop produces ABABABAHI because the first two bytes are copied again and again. Shifting left is safe forward. This decision is exactly what the library function memmove makes; memcpy does not and has undefined behavior for overlapping areas.

memmove_logic.c
#include <stdio.h> #include <stddef.h> #include <string.h> /* copy n bytes correctly even when the areas overlap */ static void my_memmove(unsigned char *dst, const unsigned char *src, size_t n) { if (dst < src) while (n–) *dst++ = *src++; /* copy forward */ else if (dst > src) { dst += n; src += n; while (n–) *–dst = *–src; /* copy backward */ } } static void naive_forward(unsigned char *dst, const unsigned char *src, size_t n) { while (n–) *dst++ = *src++; } int main(void) { unsigned char a[10] = “ABCDEFGHI”; unsigned char b[10] = “ABCDEFGHI”; my_memmove(a + 2, a, 5); /* shift right by 2: destination overlaps the source */ naive_forward(b + 2, b, 5); /* forward copy corrupts the data */ printf(“my_memmove : %s\n”, a); printf(“naive forward : %s\n”, b); unsigned char c[10] = “ABCDEFGHI”; my_memmove(c, c + 2, 5); /* shift left by 2: forward copy is right */ printf(“shift left : %s\n”, c); return 0; }
Output (verified by compiling and running)
my_memmove : ABABCDEHI naive forward : ABABABAHI shift left : CDEFGFGHI
Rule: Use memmove whenever source and destination can overlap; use memcpy only when you know they cannot.

Example 7: Parsing a Number List with a Cursor

Problem: Read comma-separated settings sent over a serial line. The cursor p skips spaces, strtol converts digits and stores in end the address just after the number (a pointer to pointer, Lesson 9.3), and the loop continues from there. Any other character is a syntax error, and the output array size limits the count. The result 12, 7, 255, 3 shows that spaces around the numbers are accepted.

parse_list.c
#include <stdio.h> #include <stdlib.h> #include <ctype.h> /* parse “12,7,255” into values; returns the number of values stored */ static int parse_list(const char *s, int *out, int max) { int n = 0; const char *p = s; while (*p && n < max) { while (*p == ‘ ‘) p++; /* skip spaces */ if (!isdigit((unsigned char)*p)) return –1; /* syntax error */ char *end; long v = strtol(p, &end, 10); /* end is advanced past the digits */ out[n++] = (int)v; p = end; while (*p == ‘ ‘) p++; if (*p == ‘,’) p++; /* one separator */ else if (*p != ‘\0’) return –1; } return n; } int main(void) { int v[8]; int n = parse_list(“12,7, 255 ,3”, v, 8); printf(“parsed %d values:”, n); for (int i = 0; i < n; i++) printf(” %d”, v[i]); printf(“\n”); printf(“\”4,x,6\” -> %d\n”, parse_list(“4,x,6”, v, 8)); printf(“\”1,2,3,4,5\” with room for 3 -> %d\n”, parse_list(“1,2,3,4,5”, v, 3)); return 0; }
Output (verified by compiling and running)
parsed 4 values: 12 7 255 3 “4,x,6” -> -1 “1,2,3,4,5” with room for 3 -> 3
Embedded note: strtol is available in newlib-nano on the STM32, but scanf-family functions pull in much more code. A hand-written cursor parser is small and predictable.

Example 8: Sliding-Window Average

Problem: Smooth ADC readings with the average of the last four samples. Two pointers mark the window: front is the newest element, back the oldest; their difference tells how many samples the window holds (growing up to four at the start). Instead of re-adding four values each time, the running sum adds the new sample and subtracts the one that leaves. The spike of 400 at index 3 is spread over the next four outputs: after four samples (100, 110, 90, 400) the average is 175; as it leaves the window the average returns to about 100. The 32-bit sum prevents overflow of the 16-bit samples.

moving_avg.c
#include <stdio.h> #include <stdint.h> #include <stddef.h> #define WIN 4 static void moving_average(const uint16_t *in, size_t n, uint16_t *out) { uint32_t sum = 0; const uint16_t *front = in; /* element being added */ const uint16_t *back = in; /* element being removed */ for (; front < in + n; front++) { sum += *front; if (front – back >= WIN) sum -= *back++; /* window longer than WIN: drop the oldest */ size_t count = (size_t)(front – back) + 1; out[front – in] = (uint16_t)(sum / count); } } int main(void) { uint16_t adc[8] = { 100, 110, 90, 400, 105, 95, 100, 110 }; /* a spike at index 3 */ uint16_t avg[8]; moving_average(adc, 8, avg); printf(“raw :”); for (int i = 0; i < 8; i++) printf(” %4u”, adc[i]); printf(“\n”); printf(“average :”); for (int i = 0; i < 8; i++) printf(” %4u”, avg[i]); printf(“\n”); return 0; }
Output (verified by compiling and running)
raw : 100 110 90 400 105 95 100 110 average : 100 105 100 175 176 172 175 102
Performance: The running sum makes the cost per sample constant, independent of the window size: important when the filter runs in a 1 kHz timer interrupt.

Example 9: Mini Exercises

Exercise 1: What is sizeof(table) in Example 2 and how many words does the loop process?
16 bytes; 4 words (16 / 4).
Exercise 2: Why does while (n--) run exactly n times?
The test uses the old value of n and then decrements; when n reaches 0 the loop ends.
Exercise 3: In Example 3, what makes the loop stop for an odd length?
The pointers meet at the middle element, so lo < hi becomes false.
Exercise 4: Why does the ring buffer need the counter used?
When head equals tail the buffer can be completely full or completely empty; the counter tells which.
Exercise 5: What is the type of m[r] for int m[3][4]?
int [4], an array of four ints, which decays to int * in expressions.
Exercise 6: When must the copy run backward?
When the destination is above the source and the areas overlap.
Exercise 7: Why is the sum in Example 8 declared uint32_t?
Adding several 16-bit samples can exceed 65535; a 32-bit accumulator cannot overflow for realistic window sizes.

Key Takeaways from the Pointer Arithmetic Examples in Embedded C

  • These pointer arithmetic examples in embedded C show that *p++ combines access and step in one expression.
  • A pointer type fixes the step: bytes, half-words or words.
  • Two pointers moving towards each other process symmetric problems without indices.
  • Ring buffers wrap a pointer by comparing it with buf + CAP.
  • Overlapping copies must choose the direction; use memmove.
  • A running sum with front and back pointers makes a sliding-window filter cheap.

Ready for the quiz?

Next: predict pointer-arithmetic results, find the off-by-one bugs and answer the interview questions.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →