What are Pointer Offsets in C Strings- C Programming Training Institute In Hyderabad

🚀 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 →

Free C Programming Course · Strings

Pointer Offsets in C Strings

Master c string pointer arithmetic: slice string tails, move cursors and pass offsets to functions in embedded C.

Almost every embedded firmware project carries small text fragments: a serial port setting, a modem command, a device name, a version banner. Pulling useful pieces out of those fragments without wasting RAM is where c string pointer arithmetic earns its keep. In this lecture of our free C programming course you will learn how a pointer plus a number gives you the tail of a string for free, why an array name refuses to move while a pointer variable moves happily, and how to hand such offsets to functions safely.

What You Will Learn

  • What base + n really means for a char array or a char pointer
  • Why a pointer to the middle of a string is itself a complete, valid string
  • The difference between an array name and a pointer variable, and why only one can be reassigned
  • How to pass a string offset to a function and read numbers out of it with strtol
  • How to avoid running past the terminating NUL when you move a cursor
  • Where this technique shows up in real embedded C programming

Prerequisites

This is part of a free C tutorial that builds step by step, so you should already be comfortable with basic pointers (the lectures on pointer arithmetic and arrays), with the idea that a C string is a run of characters ending in a NUL byte, and with compiling a small program using gcc. If any of that is shaky, revisit the earlier string lectures first. Everything below was compiled with GCC 13 using -std=c11 -Wall -Wextra, and the outputs shown are real.

Why C String Pointer Arithmetic Matters for Embedded Systems

On a microcontroller with a few dozen kilobytes of RAM you rarely want to copy text around. Suppose your board receives the configuration line UART2:115200-8N1. The part before the colon names a peripheral, the middle is a baud rate, and the end describes data bits, parity and stop bits. A beginner might allocate three buffers and copy each field into its own array. A firmware engineer simply points a cursor at the first character of each field and works in place. No copy, no extra RAM, no extra cycles.

That in-place style is exactly why embedded C programming leans so heavily on pointers into existing buffers: protocol parsers, command line shells, bootloader menus, log formatters and AT-command drivers all do it. Understanding it properly is one of the biggest steps from classroom C to production C, and it is a core topic in any serious free embedded C course.

Array Name Versus Pointer Variable

When you write char port_cfg[] = "UART2:115200-8N1"; the compiler reserves 17 bytes (16 characters plus the NUL) and gives the group a name. In most expressions that name behaves like the address of the first element. So port_cfg + 6 means “the address six characters further on”, and because each char is one byte, the arithmetic is exactly six bytes. For wider types the compiler scales the step automatically, but for characters the scale factor is one.

A pointer variable such as char *cur is a separate object that stores an address. You can change what it stores. The array name is not an object that stores an address at all; it simply is the location of the array. That one sentence explains the compile error you will see shortly, and it is the heart of c string pointer arithmetic.

PropertyArray name (port_cfg)Pointer variable (cur)
What it isThe block of characters itselfA variable holding an address
Can be reassignedNoYes
sizeof resultWhole array, 17 bytes hereSize of a pointer, 8 bytes on a 64-bit PC, usually 4 on a Cortex-M
Can do name + 6Yes, gives a new addressYes, gives a new address
Can do name += 6NoYes

Memory view of port_cfg and a cursor at offset 6

index012345678910111213141516
byteUART2:115200–8N1\0
port_cfg→index 0
cur = port_cfg + 6→index 6
The highlighted cells are what printf with %s prints when given cur

Walking Through C String Pointer Arithmetic in Code

The program below creates the array, prints it whole, prints it from offset 6, then moves a pointer variable forward and prints again. Notice how strlen(cur) reports the length of the remaining text, not the whole array. A string function only cares about where the NUL is; it has no idea that characters existed before the pointer you handed it.

#include <stdio.h>
#include <string.h>

int main(void)
{
    char port_cfg[] = "UART2:115200-8N1";
    char *cur;

    printf("full    : %s\n", port_cfg);
    printf("offset 6: %s\n", port_cfg + 6);

    cur = port_cfg + 6;
    printf("*cur    : %c, cur: %s\n", *cur, cur);

    cur += 7;
    printf("moved   : %s (len %zu)\n", cur, strlen(cur));
    return 0;
}

Build and run it:

gcc -std=c11 -Wall -Wextra -o p42a p42a.c
./p42a

Expected output:

full    : UART2:115200-8N1
offset 6: 115200-8N1
*cur    : 1, cur: 115200-8N1
moved   : 8N1 (len 3)

Two details deserve attention. First, *cur is a single char, so it is printed with %c, while cur itself is the address of a whole tail and is printed with %s. Mixing those up is one of the most common beginner mistakes. Second, after cur += 7 the pointer sits on the digit 8, because six characters of baud rate plus the dash occupy offsets 6 to 12, leaving offset 13 as the first character of the framing field.

Why Moving an Array Name Fails

Now try to move the array name itself, as if it were a cursor:

#include <stdio.h>

int main(void)
{
    char port_cfg[] = "UART2:115200-8N1";

    port_cfg = port_cfg + 6;
    printf("%s\n", port_cfg);
    return 0;
}

GCC refuses to build it:

p42bad.c: In function 'main':
p42bad.c:7:14: error: assignment to expression with array type
    7 |     port_cfg = port_cfg + 6;
      |              ^

The message is precise. An array is not a modifiable value; its address is fixed for the lifetime of the variable. If you need a moving position, create a separate pointer and move that. This is the first rule of safe C string pointer arithmetic: never try to shift the array, shift a cursor into it.

A Pointer Into the Middle Is Still a String

A C string is defined by where it starts and where the first NUL appears. Nothing says the start must be the first byte of an allocation. When you point at offset 6 of UART2:115200-8N1, the text from there to the NUL is a perfectly legal string whose content is 115200-8N1. This is why printf("%s", port_cfg + 6) works without any copying: the tail shares the same terminator as the original.

This also explains an important caution. Because the tail and the original share one NUL, a write through the tail changes the original array. If you shorten the tail by placing a NUL somewhere inside it, the original string becomes shorter too. That is sometimes exactly what you want (splitting a line into two strings in place) and sometimes a nasty surprise, so be deliberate.

Two strings sharing one terminator

index012345678910111213141516
byteUART2:115200–8N1\0
tail␣␣␣␣␣␣115200–8N1\0
Original string: indexes 0-15. Tail string: indexes 6-15. Same NUL at index 16

Passing a String Offset to a Function

Functions that take a const char * do not care whether you give them a whole string or a tail. That makes offsets a natural way to say “start parsing here”. The second program prints two tails through a helper and then extracts the baud rate using strtol. The function strtol is worth learning because it tells you where it stopped through its second argument, so you can continue parsing from that exact spot.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void show_tail(const char *s)
{
    printf("tail -> %s (len %zu)\n", s, strlen(s));
}

int main(void)
{
    const char cfg[] = "UART2:115200-8N1";
    char *end;
    long baud;

    show_tail(cfg + 6);
    show_tail(cfg + 13);

    baud = strtol(cfg + 6, &end, 10);
    printf("baud=%ld, stopped at '%c', rest=%s\n", baud, *end, end);
    return 0;
}
tail -> 115200-8N1 (len 10)
tail -> 8N1 (len 3)
baud=115200, stopped at '-', rest=-8N1

Look at the last line. strtol consumed the six digits, stopped at the dash, and stored that address in end. You can now do end + 1 to skip the dash and continue. This “cursor” pattern, where each parsing step returns the position for the next, is the backbone of hand written embedded parsers.

The Cursor Pattern in Practice

  1. Keep one pointer that always marks the first unread character.
  2. Call a helper that reads a field and returns the new position (or updates the pointer through a pointer-to-pointer).
  3. Check for the NUL after every step so a short or damaged message never carries you past the end.
  4. Never write through the cursor unless the buffer is a modifiable array, not a string literal.

Bounds: How Far Can an Offset Go?

The language allows you to form an address up to and including one position past the last element. For a string this means s + strlen(s) is legal and points at the NUL, which makes it an empty string. Going further, or before the beginning, is undefined behaviour even if you never dereference it. The compiler will usually not warn you, and on a microcontroller the symptom may be silent corruption instead of a crash, which is much harder to debug.

A practical rule for c string pointer arithmetic: whenever an offset comes from data (a length field, a delimiter search, user input), compare it against strlen or against your buffer size before using it. When the offset comes from a constant like the 6 above, a comment explaining where the number came from will save the next reader an afternoon.

Common Mistakes in C String Pointer Arithmetic

MistakeWhat happensFix
Trying name = name + n on an arrayCompile error: assignment to expression with array typeUse a separate char * cursor
Printing a tail with %cPrints one character, or garbage if you pass an addressUse %s for an address, %c for *ptr
Offset larger than the string lengthUndefined behaviour, often a silent wrong readCheck against strlen first
Writing through a tail of a literalCrash or hard faultCopy to an array, or declare the pointer const
Forgetting that tail and original share the NULEditing the tail changes the originalCopy first when you need independence

Warning: a hard-coded offset such as 6 silently breaks the day someone renames UART2 to UART10. Prefer searching for the delimiter with strchr and using the returned address, instead of counting characters by hand.

Best Practices for String Pointer Arithmetic in Embedded C

  • Declare read-only views as const char * so the compiler stops accidental writes.
  • Keep the original base pointer in its own variable; move only the copy.
  • Search with strchr or strtol‘s end pointer instead of counting characters by eye.
  • Compile with -Wall -Wextra and treat warnings as errors in CI.
  • Test the shortest and longest inputs your protocol allows, including an empty string.

Performance: forming an offset costs a single addition and no memory traffic, which is why parsers written this way are fast on small cores. Security: most remote exploits in text protocols come from trusting an offset or length that arrived over the wire. Validate before you add.

Summary and Key Takeaways

  • For a char array or pointer, p + n moves exactly n bytes forward.
  • Good c string pointer arithmetic keeps every address between the first character and the NUL.
  • The result of that addition is a valid string whenever it stays inside the original, because the NUL is shared.
  • An array name cannot be reassigned; a pointer variable can.
  • strtol reports where it stopped, which makes in-place parsing easy.
  • Stay between the first character and the NUL; validate any data-driven offset.

Conclusion: C String Pointer Arithmetic in Your Own Code

You now know why c string pointer arithmetic, a pointer plus a number, is one of the cheapest and most useful operations in C, and you have seen the compiler enforce the difference between an array and a pointer. Practice by writing a tiny parser that splits NAME=VALUE lines using only strchr, strlen and offsets, and try feeding it empty strings and lines with no equals sign. That single exercise covers most of what this free C tutorial has taught about strings so far, and it is exactly the kind of code that appears in real embedded C programming interviews. In the next lecture we look at string literals themselves and the surprising things you can do with them.

Frequently Asked Questions

What is c string pointer arithmetic?

It is adding or subtracting an integer to a pointer that points into a character array. For char pointers the step is one byte, so s + 6 points at the seventh character, and the text from there to the NUL is itself a valid string.

Why can I not do array_name = array_name + 1 in C?

An array name is not a modifiable object holding an address. It denotes the fixed location of the array, so assignment to it is rejected with the error “assignment to expression with array type”. Use a separate pointer variable as a cursor.

Is a pointer to the middle of a string a valid string?

Yes. A C string only needs a start address and a terminating NUL. A tail pointer shares the original terminator, so functions like printf, strlen and strtol treat it as a complete string.

What is the difference between %c and %s when printing a char pointer?

Use %c with a single character such as *p, and %s with an address such as p. Giving %s a character value or %c an address leads to wrong output or a crash.

How far can I move a string pointer safely?

Up to the NUL terminator, which sits at s + strlen(s). Forming an address beyond that point, or before the start of the array, is undefined behaviour.

Does pointer arithmetic on strings use extra memory?

No. You only compute a new address, so no characters are copied. That is why the technique suits RAM-limited microcontrollers.

Is this lecture part of a free embedded C course?

Yes. It belongs to the free C programming course on EmbeddedPathashala, written for students learning C for embedded systems, with every example compiled and run before publishing.

Keep Going With the Free C Course

EmbeddedPathashala is a free C programming course and free embedded C course built for students. Practice every example on your own machine, then move on to the next lecture.

💬 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 →