Summary
In this lesson, you learned that:
- Every variable is stored in memory and has an address.
&xis the address of the variablex, and%pprints it. - A pointer is a variable that holds an address:
int *p = &x;. Its type says what it points to:int *,double *,char *. *pis the valueppoints to (dereferencing). You can read it,printf("%d\n", *p);, and change it,*p = 20;. Without the star,p = &y;changes where the pointer points.- In a declaration,
*makes a pointer. Before a pointer, it gets the value from the address. Between two values, it multiplies.&and*are opposites. - A function with a pointer parameter can change the caller's variable:
void add_bonus(int *points, int bonus), called asadd_bonus(&score, 5). A forgotten&in the call is a compile error; a forgotten*inside the function is a bug without any error. - Through pointers, a function can swap two variables or give back several results at once (output parameters).
- The name of an array is the address of its first element, so
int *p = numbers;andp[1]work. A parameterint numbers[]is a pointer, the same asint *numbers. That's why a function changes the caller's array and needs its count. NULLis a pointer that points nowhere. A function that returns a pointer, such as the address of an element it found, returnsNULLwhen there is none. Check a pointer that can beNULLbefore you use it:if (p != NULL). Reading throughNULLstops the program here withRuntimeError: unreachable.const int *numbersis a pointer that the function only reads through. Text in quotes gets aconst char *pointer:const char *name = "Anna";.
In the next lesson, on structures, you'll learn to group values that belong together, such as a student's name and points, into one variable. Pointers will come in handy there too.
Instructions
- 1
Let's practice. The array
scoresholds the results of a test, and the teacher adds a bonus to each one. Abovemain, write a functionadd_bonuswith the parametersint *scores,int countandint bonus. It adds the bonus to every score, but no score may go over 100 points: a higher one becomes 100. Call it with the bonus10before the loop. The program prints55,82,100,48and76, one per line. - 2
Below
add_bonus, write a functionfind_min_maxwith the parametersconst int *scores,int count,int *lowestandint *highest. Through the two pointers, it stores the lowest and the highest score, so it gives back two results at once. Start by storing the first element in both. At the end ofmain, create two variables, pass their addresses to the function and print them:Lowest: 48, highest: 100.