Workshop: Functions with Pointer Parameters | Programming in C

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

Workshop: Functions with Pointer Parameters

Programming in C · Chapter 9: String Manipulation via Pointers, File Streams, and File HandlingSection 9.3 · lesson 56 of 787 min · free with a free account

← Workshop: Navigating Data with Pointer OffsetsNext lesson: The Stream I/O Model 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

Returning several results and success flags through pointer parameters in C.

  • Use pointer parameters to send more than one result back to the caller
  • Explain why passing a variable instead of its address fails to compile
  • Return a 1 or 0 status while sending data out through a pointer
  • Write through an output pointer only on the success path

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

Opening Question

One Call, More Than One Answer

A function can hand back only one value with return. But Priya's arcade tool needs the lowest and the highest score from one call. And it needs to know whether a typed score was even a number. So how does one call send back more than one thing? Give it the addresses of empty boxes, and let it fill them.

Output Parameters

Filling the Caller's Lo and Hi

Here's the idea from six point five. A function gets a copy of each argument. But when the argument is an address, the copy still points at the caller's box. So main makes two empty boxes, lo and hi, and passes ampersand lo and ampersand hi. Inside, min and max hold those addresses. The function writes through them, with star min and star max, starting from the first score. The row comes in as const int star, plus its length, because it's only read. The loop starts at a plus one, since box zero is already used. min_max itself returns nothing: void. Its results are the two boxes it filled. Build and run: lowest 48, highest 95.

Common Mistake

Forgetting the Ampersand

A common slip is passing lo instead of ampersand lo. So delete the ampersand. Now build again. Clang stops you: incompatible integer to pointer conversion. The function expects an address, and it got a whole number. It even suggests the fix: take the address with ampersand. Passing the address is what gives the function permission to write.

Status and Data

Rescaling Scores Without Dividing by Zero

The arcade also wants every score on a zero to one hundred scale. The lowest becomes zero, and the highest becomes one hundred. normalize gets lo and hi by calling min_max, with the same ampersands. Then it walks the row, and writes each new value over the old one. The rule is score minus lo, times one hundred, divided by hi minus lo, in whole numbers. For 72, that's 2400 over 47, which is 51. One case breaks the rule. If every score is equal, hi minus lo is zero. Dividing by zero is undefined, and it can crash. So normalize checks first. It returns zero, and leaves the row alone. Otherwise, after the loop, it returns one. Build and run. The first call says done equals one, and the row is rescaled. Then three equal scores: done equals zero, and fifty, fifty, fifty is untouched. Two channels: the array carries the data, and the one or zero says whether the job was done.

Quick Check

A Missing Star Loses the Answer

Quick check. Maya has four lap times, and this function should report her fastest lap through a pointer. What does it print? Pause and predict. It prints best lap 31. Look at the line inside the if: best equals p, with no star. That re-aims the function's own copy of the pointer. After the first write, nothing goes through best again, so b in main keeps thirty-one. Twenty-six needs star best equals star p. Fix it, run again, and now it's best lap 26. One missing star, and the answer never reaches the caller.

Success Flag

Parsing a Score Through a Pointer

One more problem. When a player types a score, the arcade gets text, such as 250, or 12x. Turning text into a number can fail. A return value can't be both a score and an error, because any int, even zero or minus one, could be a real score. So parse_score returns yes or no, as one or zero. The number goes out through a pointer parameter, out. The loop walks the text with a char pointer, as in nine point one. C promises the digits are in order, so star p minus the character zero is the digit. Anything that isn't a digit is a failure. So is empty text, and so is a value over a thousand. And star out is written only on the success path, at the very end. main starts v at minus one, which means nothing was written. It tries five texts, one at a time. Build and run. 250 and 1000 pass. 12x fails on the x, the empty text has no digits, and 1001 is over the limit. Every time it fails, v is still minus one, because the function never wrote to it. That's the same shape as scanf, which returns how many items it read, and fills the boxes you gave it.

Story Resolved

Is Zero a Score or a Failure

Sam tested Priya's first parser by typing a blank line. It returned zero for the score, and printed score accepted: zero. "Is zero a real score, or a failure?" Sam asked. "It can't be both," Priya said. She changed the function to return one or zero, and send the number through a pointer. Now a blank line prints try again, and zero stays a good score.

Quick Check

A Failed Call Leaves R Alone

Quick check. safe_div returns zero instead of dividing by zero. main calls it twice with the same r, then prints both results and r. What will it print? Pause and predict. It prints 1 0 4. Nine over two, in whole numbers, is four. The first call succeeds, and writes that four into r. The second call fails before it writes anything, so r keeps the four. Seven was replaced by the first call. And zero is never written: a failure leaves r alone.

Key Takeaways

Addresses In, Flags Out

To recap. Pass an address, like ampersand lo, to let a function write into your box. Inside, write through the pointer with a star. Return one or zero to say whether it worked. And write the value through the pointer only when it did.

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 Workshop: Functions with Pointer Parameters

What does incompatible integer to pointer conversion mean in C?
It means an int value was used where a pointer was expected, most often in a call to a function that wants an address, because the ampersand was left off. With void min_max(const int *a, int n, int *min, int *max), the call min_max(scores, 6, lo, hi) passes the values of lo and hi, and Clang flags it. The fix is min_max(scores, 6, &lo, &hi), because passing the address is what lets the function write into the caller's variables.
Why does assigning to a pointer parameter not change the caller's variable in C?
Assigning to the parameter itself, as in best = p;, only re-aims the function's own copy of the pointer. To change the caller's variable, write through the pointer with a star: *best = *p;. Both lines are valid C, so the compiler accepts the mistake, and the caller's variable simply keeps its old value. One missing star means the result never reaches the caller.
How should a C function report an error when any int could be a valid result?
Return a status, 1 for success and 0 for failure, and send the result out through a pointer parameter. A function like int parse_score(const char *text, int *out) can then reject 12x, empty text, or a value over 1000 without confusing failure with a real score of 0. Write *out only on the success path, so a failed call leaves the caller's variable unchanged, much as scanf does.
How do you avoid division by zero when rescaling scores to 0 to 100 in C?
Check the divisor before dividing. The rescaling rule (score - lo) * 100 / (hi - lo) maps the lowest score to 0 and the highest to 100, so with lo 48 and hi 95, a score of 72 becomes 2400 / 47, which is 51 in integer division. If every score is equal, hi - lo is 0, so a safe function returns 0 and leaves the array untouched.

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 →