Pointer-Based String Processing, Explained with Code Examples

UPI Study › Courses › Programming in C › Free lessons › Lesson 9.1 Free with a free account

Pointer-Based String Processing

Programming in C · Chapter 9: String Manipulation via Pointers, File Streams, and File HandlingSection 9.1 · lesson 54 of 788 min · free with a free account

← Passing Array Addresses to FunctionsNext lesson: Workshop: Navigating Data with Pointer Offsets →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

In this lesson

Walking, measuring, copying, and joining C strings with char pointers.

  • Walk a string with a char pointer until it reaches the null terminator
  • Write your own strlen using pointer subtraction
  • Copy and concatenate strings with two moving pointers
  • Check that a joined string fits its buffer before writing

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,085 words). Read along, or search it.

Opening Question

Reading Text With Your Finger

Think of reading a line of a book with your finger. You touch the first letter, move to the next, and keep going until the line stops. A C string is read the same way, and your finger is a pointer. But how does a pointer know where the text stops? Today, a pointer walks along text. You'll build your own length and join functions, change letters in place, and check that the result fits, all without a single index.

Pointer Walk

Step Until the Marker

From seven point five, a string is a row of char boxes, ending with a box holding backslash zero. From eight point three, p plus plus moves a pointer to the next box. Put the two together, and you get the oldest trick in C. Point at box zero. Then repeat: look at star p, and if it isn't the marker, use it, and step forward. The loop test asks: is the box I'm touching the end marker? Build and run. S, t, a, r, and a count of four. The marker isn't counted, though the array has five boxes. Nobody told the loop how long the string is. The string itself says so, and that's why this walk works on any text.

Your Own Strlen

End Minus Start Is the Length

The library's strlen, from seven point six, does exactly this walk. You can write it with a second pointer instead of a counter. Let end start at the same place as s, and slide right until it touches the marker. Then end minus s is the number of boxes between the two. That's pointer subtraction, from eight point three, and it's the length. For an empty string, end never moves, so the answer is zero.

Worked Example

Copying and Joining With Two Pointers

Here's my strlen, as code. Its parameter is const char star s, because it only reads the text. It promises not to change it, as in eight point six. To copy a string, walk the source, and put each char in the matching box of the destination. Two pointers move together. The last step is easy to forget: write a backslash zero after the final char. A copy is only a string if it ends with the marker. To concatenate, which means to join one string onto the end of another, first move the destination pointer to its own backslash zero. Then copy the new text, starting right on top of that marker. The copy brings its own marker, so the joined text ends properly. Main copies Star into title, then joins light, and then a space and Arcade. Build and run. Starlight Arcade, sixteen chars.

Quick Check

Stopping on the First Space

Quick check. A pointer walks the text level up, and stops on the first space. Then the program prints p minus s, and the string that starts at p plus one. What does it print? Pause and predict. It prints 5 up. The space sits at index five, after l, e, v, e, l. So p minus s counts five boxes. p plus one is the address just after the space. Percent s starts printing there, and stops at the marker: up. Six would count the space itself. But p stops on the space, and the distance to it is five.

In-Place Changes

Shouting and Flipping Through a Pointer

A function that receives char star s, without const, may write through it. The change shows up in the caller's array. That's in place: no second array. In ASCII, which this Mac uses, capitals sit the same distance from capital A as small letters from small a. So star p, minus small a, plus capital A, gives the capital. The test, between small a and small z, leaves digits and spaces alone. The portable way is toupper, from seven point six, which doesn't rely on ASCII. The second function, flip, swaps chars in place: one pointer at each end, swap, and move both toward the middle until they meet. Right starts at s plus strlen of s, minus one: the last real char. Swapping the marker to the front would end the string at once. Build and run. The text star 9 becomes STAR 9, in capitals, then 9 RATS. That is shouting, and flipping, in place.

Common Danger

Text in Quotes Is Read-Only

One warning. If you write char star a equals star in quotes, that pointer aims at text stored inside the program, and that text is meant to be read only. Changing a letter through it is undefined behavior. It compiles without a word from clang, and it usually crashes. Write char b, empty brackets, equals star, instead. That makes a private array you may change.

Size Check

A Join That Refuses to Overflow

A pointer loop will happily write past the end of a row, because it doesn't know where the row ends. The destination of a join must hold both strings, plus one box for the marker. So safe cat receives the buffer's size, adds up what's needed, and refuses if it won't fit. Refusing means returning zero, and changing nothing. Its copy loop uses the common one-line form: star dest plus plus equals star src plus plus. Copy the char, then move both pointers. In main, sizeof buf works, because buf is a real array there. Build and run. Light fits, so the answer is one: Starlight. Then space Arcade would need seventeen boxes, and buf has sixteen. Zero, and buf is unchanged.

Story Resolved

A Thirty-Letter Name in Sixteen Boxes

At the Starlight Arcade, Priya wrote a function to build a name tag: a first name, a space, then the player's level. It worked for Ana, and for Sam. Then Sam typed a thirty-letter name into a sixteen-box buffer. "It printed fine on my screen," Priya said, "but it also scribbled on the next variable." She added the size check that afternoon. "Now it says no, instead of quietly breaking something."

Quick Check

A Join That Fits Exactly

Quick check. An eight-box buffer holds Star. Before adding Gun, the program works out how many boxes the join needs. What does it print? Pause and predict. It prints 8: yes. Four letters of Star, three of Gun, plus one for the marker: eight boxes. The buffer has exactly eight. Eight isn't more than eight, so the join fits exactly, marker included. Answering no is the tempting slip, but a buffer filled to its last box is fine. And seven forgets the marker box.

Key Takeaways

Walk, Measure, Copy, Join, Check

To recap. Walk a string with a char pointer until star p is backslash zero. Your own strlen slides an end pointer to the marker, and end minus s is the length. Copy char by char and end with a marker. To join, advance to the destination's marker first. And before writing, check that the result fits: both lengths, plus one.

About Programming in C at UPI Study

Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Pointer-Based String Processing

How do you loop through a string with a pointer in C?
Point a char pointer at the first character and repeat while *p is not '\0': use the character, then step with p++. For example, for (const char *p = s; *p != '\0'; p++) visits every character and stops at the null terminator. The loop needs no length, because the string's own terminator says where it ends, so the same walk works on text of any length.
How do you write your own strlen function using pointers in C?
Start a second pointer at the beginning of the string, slide it forward until it reaches the null terminator, then subtract: size_t my_strlen(const char *s) { const char *end = s; while (*end != '\0') end++; return end - s; }. Pointer subtraction counts the characters between the two addresses, and for an empty string end never moves, so the result is 0. The parameter is const because the function only reads.
How do you concatenate two strings in C using pointers?
First move a pointer on the destination to its null terminator, then copy the source character by character starting on top of that terminator, and finally write a new '\0'. A compact copy loop is while (*src) *dest++ = *src++; followed by *dest = '\0';. The destination must have room for both strings plus one element for the terminator, or the loop writes past the end of the array.
How do you check that a joined string fits in a buffer in C?
Add both lengths plus one for the null terminator, and compare the total with the buffer size: the join fits if strlen(dest) + strlen(src) + 1 <= size. For an 8-element buffer holding Star, adding Gun needs 4 + 3 + 1 = 8, which fits exactly. Joining Starlight with a space and Arcade needs 17, so a 16-element buffer must refuse and stay unchanged.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Programming in C.

78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Programming in C
3 credits · NCCRS
Enroll →