QUESTION 06 · Pointers and Functions
Explain how pointer arguments allow a function to modify caller data.
5 marksAnswer in brief
A function can receive a pointer to a caller’s object and modify the object through that pointer.
Function interface
void set_value(int *p, int value);
Working
- The caller passes &number and the new integer value.
- The parameter p receives a copy of the address.
- The assignment *p = value changes the caller’s number object.
Example trace
number begins at 10. set_value(&number, 30) gives p the address of number and gives value the integer 30. The function checks p against NULL, then writes through it. After returning, main prints 30 because number itself was changed.
Value versus target
Changing p to NULL inside the function would only change the local pointer parameter. It would not replace a caller’s pointer variable. Changing *p updates the target. To update a caller’s pointer object, an additional level of indirection can be used, as shown in the pointer-to-pointer topic.
Validity
A non-null test is useful but does not prove every pointer is valid. The caller must still provide a pointer to a live, writable int object. A dangling pointer can be non-null. The example passes the address of a local object whose lifetime includes the complete call.
Complexity
The function performs a fixed comparison and at most one fixed-size assignment. Time and auxiliary space are O(1). Passing an address does not require copying every byte of a larger object that might be reached through it.
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
void set_value(int *p, int value)
{
if (p != NULL) { *p = value; }
}
int main(void)
{
int number = 10;
set_value(&number, 30);
printf("Number = %d\n", number);
return 0;
}
Sample input and output
This example uses values already written in the program.
Output
Number = 30
Related exam questions
Related questions in the pointer function arguments category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
View this category in the exam question bank →