QUESTION 09
How can a function change the caller’s structure?
2 marksAnswer
Pass a pointer to the caller’s structure and assign through it. Passing a structure by value instead gives the function its own parameter copy.
QUESTION 09
Pass a pointer to the caller’s structure and assign through it. Passing a structure by value instead gives the function its own parameter copy.
QUESTION 10
A function can receive a structure value for reading or a pointer for access to the caller’s object.
void display(struct Student s) receives a structure value. Changes to s.roll or s.marks inside that function affect only the parameter object. This provides a simple interface when a record should not be replaced by the function.
void update(struct Student *p) can assign p->marks. The arrow operator accesses a member of the structure identified by p; p->marks means (*p).marks. The caller passes &student. A reading function can take const struct Student *p to prevent member modification through that access.
The complete example starts with marks 70. update(&s, 80) receives the address and assigns p->marks = 80. main then displays 80, because the original object was modified. Passing a pointer is still C pass by value: the copied value is an address.
A pointer must identify a live, suitable structure object. Checking against NULL does not prove every non-null address is valid. Output can be a returned scalar, a returned structure or an object changed through a pointer, depending on the interface.
For this fixed-size record, the update takes O(1) work and space. For larger records, value passing can involve copying the record representation; using a pointer avoids explicitly requesting a full record copy at the source interface. Pointer members still need separate ownership rules.
/* CodeBhavya | Data Structures AR25 | Learning example */
#include <stdio.h>
struct Student { int roll, marks; };
void update(struct Student *p, int marks)
{
if (p != NULL) { p->marks = marks; }
}
int main(void)
{
struct Student s = {101, 70};
update(&s, 80);
printf("Marks = %d\n", s.marks);
return 0;
}The example uses values in the code.
Marks = 80