String Representation in C, Explained with Code Examples

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

String Representation in C

Programming in C · Chapter 7: Arrays, Strings, Input Validation, and Formatted OutputSection 7.5 · lesson 44 of 786 min · free with a free account

← Multi-Dimensional Arrays in CNext lesson: Standard String Library Functions →

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

In this lesson

How C stores text as char arrays ending in a null terminator.

  • Explain the role of the null terminator in a C string
  • Calculate how many char elements a string of n letters needs
  • Compare the sizeof an array with the length of the string it holds
  • Read and print a single word using scanf and printf with %s

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 (835 words). Read along, or search it.

Opening Question

Text With No Ready-Made Box

The arcade's welcome screen says: Welcome, Priya! Some languages have a ready-made box for text. C doesn't. In C, a piece of text is just a row of char boxes, with one secret rule: the row must end with a special marker, so the computer knows where the words stop. Learn that one rule, and every string trick in C starts to make sense.

Null Terminator

A Char Array With an End Marker

A char holds one letter, like S in single quotes. A whole name needs many letters in a row, and you already know how to make a row: an array. So a string in C is an array of char. But an array doesn't remember how many letters you used, so C adds a marker box after the last letter. It's the character backslash zero, called the null terminator, because it ends the string. Its value is the number zero, and no letter is zero. So Sam needs four boxes: three letters, and the marker. A string with n letters always needs n plus one boxes.

Building by Hand

Setting Every Box Including the Marker

Here's the slow way to build Sam: set each box yourself, and don't forget the marker. Percent s in printf means: print a string here. It keeps printing boxes until it meets the marker. Run it. The word is Sam. And the marker is a real box with a real number: the last line shows the zero stored in box three.

String Literals

Double Quotes Add the Marker for You

Typing every letter is slow. So C lets you write text between double quotes: a string literal. The compiler quietly adds the marker for you. Leave the size empty, and C counts the boxes: letters plus the marker. Give a bigger size, and C fills the unused boxes with zero. This loop finds the length another way: count boxes until you meet the marker. Run it. Sizeof name is four. Sizeof label is twelve, though the word is still Sam: sizeof counts boxes, not letters. The loop stops at three. And mind the quotes. S in single quotes is one char, one box. S in double quotes is a string: two boxes, the letter and the marker.

Quick Check

Sizes of Two Pinball Arrays

Quick check. Two arrays hold the word Pinball. One lets C count, and one asks for ten boxes. What two sizes print? Pause and predict. Eight, then ten. Pinball has seven letters, and C adds one box for the marker. Slot asked for ten boxes, so it has ten, whatever the word. Seven would forget the marker's box.

Reading a Word

Scanf With Percent S and a Width

To print a string, use percent s. To read a word from the keyboard, scanf takes percent s too. There's no ampersand before the array's name. The name already stands for where the array lives, as in lesson 7.3. The nine means read at most nine letters. The array has ten boxes, and one must stay free for the marker that scanf adds. Run it, and type Priya. Welcome, Priya! Percent s also stops at the first space. Type Priya Sharma, and the name is only Priya. Lesson 7.7 reads whole lines.

Shortening a String

Planting a Marker in the Middle

Because percent s stops at the first marker, you can shorten a string just by planting a marker in the middle. Run it. Before, Starlight. After, Star. The letters after the new marker are still in their boxes: box five still holds i. But a string ends at its first marker, so they're no longer part of it.

Common Mistake

No Box Left for the Marker

What if the marker isn't there? This array has exactly three boxes, for a three-letter word. C allows it, because the letters fit. But the marker has no box left. Apple's clang builds it without a word, even with dash W extra. Newer GCC versions warn. This program only prints the size, on purpose. Print tag with percent s, and printf walks past the last box, looking for a zero. That's undefined behavior: extra symbols, a crash, or something that looks fine today. The fix is one box more than the letters.

Quick Check

A Marker Changes the String, Not the Array

Quick check. Here's the word Arcade, with a marker planted in box three. Then printf shows the string, and the array's size. What prints? Pause and predict. Arc, then seven. A R C, and the string ends at the new marker in box three. But the array still has seven boxes: six letters plus the original marker. A marker changes the string, not the array.

Story Resolved

Letters Plus One

Back to Priya's badge printer. Sam tested it with his own name, and on that run the badge showed Sam, followed by a few odd symbols. Your array has three boxes, Sam said, and my name has three letters. Priya changed the size to four, and the badge was clean. She wrote it on a sticky note: letters plus one.

Key Takeaways

Char Arrays, Markers, and Percent S

To recap. A string is a char array that ends with the marker, backslash zero, so n letters need n plus one boxes. A string literal adds the marker for you, and sizeof counts boxes, not letters. Percent s prints until the marker, and reads one word with no ampersand. And a string with no marker is undefined behavior waiting to happen.

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 String Representation in C

What is the null terminator in a C string?
The null terminator is the character '\0', whose value is zero, stored right after the last letter of a string. A C string is an array of char, and the array does not record how many letters are in use, so printf with %s keeps reading characters until it meets this marker. Because no letter has the value zero, the marker safely shows where the text stops.
How many characters does a C string array need?
A string with n letters needs at least n + 1 char elements: one per letter plus one for the null terminator. The word Sam needs 4, and Pinball needs 8, so char game[] = "Pinball"; has a sizeof of 8. If the array has exactly n elements, the letters fit but the terminator does not, and printing it with %s is undefined behavior.
What is the difference between 'S' and "S" in C?
'S' in single quotes is a character constant, one character that fits in a single char. "S" in double quotes is a string literal: an array of two chars, the letter S followed by the null terminator that the compiler adds. So sizeof "S" is 2. Use single quotes to set one element, such as name[0] = 'S';, and double quotes to initialize a whole string.
How do you read a word into a char array with scanf in C?
Use %s with a width one less than the array size, and no ampersand, as in char name[10]; scanf("%9s", name);. The array's name already stands for its address, and the width 9 leaves one element free for the null terminator that scanf adds. %s stops at the first whitespace, so typing Priya Sharma stores only Priya.

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 →