Pointer Fundamentals in C, Explained with Code Examples

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

Pointer Fundamentals in C

Programming in C · Chapter 8: Pointers, Pointer Arithmetic, and String Manipulation via PointersSection 8.2 · lesson 49 of 788 min · free with a free account

← Workshop: A Text Processing UtilityNext lesson: Pointer Arithmetic in C →

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

In this lesson

Addresses, pointer variables, dereferencing, and NULL in C.

  • Explain memory addresses and get a variable's address with &
  • Declare a pointer and dereference it with * to read or write a value
  • Print an address with %p and a void pointer cast
  • Use NULL for a pointer with no address yet and test it before use

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

Opening Question

A Slip That Leads to the Tokens

Picture a wall of numbered lockers at the Starlight Arcade. Priya doesn't carry your tokens around for you. Instead, she hands you a slip that says: locker 4004. You go and look. That slip isn't the tokens, but it leads straight to them. C has the same trick. It's called a pointer, and much of C is built on it.

Memory Model

A Street of Numbered Mailboxes

When a program runs, its variables live in memory. Picture memory as one very long street of tiny mailboxes. Each mailbox holds one byte, and has a number painted on its door. That number is its address. No two mailboxes share one. A char fits in one mailbox. An int uses several in a row: four on this Mac, though other machines can differ. A variable's address is the number of its first mailbox. So if tokens sits in boxes 4004 to 4007, its address is 4004. Those numbers are made up for the picture. Real addresses are much longer, as you're about to see.

Address-Of Operator

Ampersand Gives an Address to Store

You never choose where a variable goes. The system picks the spot. But you can ask where it landed. Put an ampersand in front of a variable, and you get its address. You've met it in scanf, where it tells scanf which variable to fill. An address is a value too, so it can be stored. A variable that holds an address is a pointer variable, or just a pointer. int star p reads: p is a pointer to an int. The type before the star says what lives at that address. To print an address, use percent p. The C rules say it expects a void star, a pointer to anything, so the address is cast to that. Build it and run it. tokens is twenty-five. The next two lines match, because p was filled with ampersand tokens. It's a long number in hexadecimal, with zero x in front. The last line printed star p. The star followed the address back to the value, twenty-five. More on that star in a moment. Now run it again. The address changes. The system picks a new spot each time, so never treat an address as fixed.

Common Mistake

One Star Makes Only One Pointer

One trap in declarations. In int star a, comma b, only a is a pointer. The star belongs to a, so b is a plain int. Sam hit this one. Try to store an address in b, and clang refuses: incompatible pointer to integer conversion. The fix is simple. Declare one pointer per line.

Dereferencing

Following a Pointer to Read or Write

An address is only useful if you can go there. Put a star in front of a pointer, and C goes to that address and uses what's stored there. It works for reading, and for writing too. Star p equals star p plus five means: follow p, take the number there, add five, and put the answer back. So tokens becomes thirty, though tokens isn't even named on that line. Next, p equals ampersand bonus points p somewhere else. Star p equals one fifty now writes into bonus instead. Build and run it to check. Before, twenty-five. After, thirty. bonus is one fifty, and tokens is still thirty. Moving p changed where it points, not what tokens holds. That's exactly how the swap function in six point five worked. It received addresses, followed them, and changed the caller's variables.

Reading Aloud

The Star Has Two Jobs

So the star has two jobs, and they look alike. In a declaration, like int star p, it means: this is a pointer. In an expression, like star p equals thirty, it means: go to the address. A tip for reading code aloud: say star as, the thing p points to. And say ampersand as, the address of. Then star p equals star p plus five reads: the thing p points to becomes the thing p points to, plus five.

Quick Check

Two Ints and Two Pointers

Quick check. Two ints, a and b, and two pointers, p and q. Follow every star and every ampersand carefully. What does this program print? Pause and predict. It prints 4 10. Line eight follows q to b, and stores four plus one there. So b is five. Line nine copies q into p. Now both point at b. Line ten doubles the box p points to, which is b, so b is ten. And a was never written at all, so it's still four. Eight, five would need p to still point at a. But p equals q moved the pointer. It didn't copy a value.

Null Pointers

NULL Means Pointing at Nothing

A pointer should always hold something safe. But sometimes there's no address yet, like a prize pointer before any prize is picked. For that, C has the special value NULL, from stdio dot h and several other headers. It means: this pointer points at nothing. Following a NULL pointer is undefined behavior. On a computer like this one, the operating system stops the program on the spot: a crash. So the safe habit is to start a pointer at NULL when it has no address yet, and test it before you follow it. Build and run. The first test finds NULL, so star p is never touched. Once p holds the address of prize, the second test passes, and star p is forty.

Common Danger

An Uninitialized Pointer Points Anywhere

A pointer that was never set is worse. It holds leftover garbage, so it may point anywhere, and there's no value you can test for. Following it may crash, or may quietly read or damage some other variable. Here, clang catches it: variable p is uninitialized when used here. Notice its suggestion: initialize it to NULL. This one never runs on screen. Its behavior is undefined.

Story Resolved

Testing for NULL Before Printing

Back at the arcade, Priya wrote a function that shows the winner's name through a pointer. Sam tested it on a day with no winner. The pointer was NULL, and the program crashed. Priya added one test before the print: winner not equal to NULL. Now an empty day shows, no winner yet.

Quick Check

Writing Through a Pointer Into Prize

Quick check. This program starts p at NULL, tests it twice, and writes through it once in between. What does it print? Pause and predict. It prints just B 25. The first test fails, because p is still NULL, so the A line never runs and star p is never followed. Then p gets the address of prize, and star p minus fifteen writes twenty-five into prize itself. B forty would need the write to miss prize. But star p is prize, so printing prize shows the change.

Pointer Sizes

Every Pointer Takes Eight Bytes Here

One last idea. Every pointer holds an address, so on this Mac, every pointer is the same size, whatever it points at. This program makes three pointers: to a char, an int, and a double. Each pointer's type matches what it points at. It prints the size of each pointer, then the size of the thing at the other end. Run it. All three pointers take eight bytes. The things they point at take one, four and eight. So a pointer's type tells C how many bytes to read when you follow it. In eight point three, it also decides how far a pointer moves.

Key Takeaways

Addresses, Stars, and NULL

To recap. Memory is a street of numbered mailboxes, one byte each, and an address is a mailbox number. Ampersand gives a variable's address. A pointer, declared with a star, stores it. And star p follows it, to read or to write. Print addresses with percent p and a void star cast, and expect them to change from run to run. Start a pointer at NULL when it has no address yet, and test it before you follow it.

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 Fundamentals in C

What is a pointer in C?
A pointer is a variable that holds a memory address. int *p; declares p as a pointer to an int, and p = &tokens; stores the address of tokens in it. Writing *p follows that address, so *p reads or changes tokens itself; *p = *p + 5; adds 5 to tokens without naming it. The type before the star says what kind of value lives at that address.
What is the difference between * and & with pointers in C?
The & operator gives the address of a variable, while * follows a pointer to the value stored at its address. In a declaration such as int *p, the star means p is a pointer; in an expression such as *p = 30, it means go to the address p holds. A helpful habit is to read *p aloud as the thing p points to, and &x as the address of x.
Why does int *a, b; not declare two pointers in C?
The star belongs to the variable name, not to the type, so in int *a, b; only a is a pointer and b is a plain int. Assigning an address to b makes clang report an incompatible pointer to integer conversion. To avoid the mistake, declare one pointer per line, or put a star before every name, as in int *a, *b;.
What is a NULL pointer in C, and why check for it?
NULL is a special pointer value meaning the pointer points at nothing. Start a pointer at NULL when it has no address yet, and test it, as in if (p != NULL), before following it, because dereferencing NULL is undefined behavior and usually crashes the program. An uninitialized pointer is worse: it holds leftover garbage, so there is no value you can test for.

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 →