Pointers and C Structs
A struct defines a "record" type which is similar to a simple C++ class with only public data members.
- Define a struct with name Pair to hold two integers:
struct Pair { int x; int y; };
This only defines the type. It doesn't create any variable storage yet.
The name of the type includes the struct keyword. So the name of the type above is struct Pair , not simply Pair
- Declare a variable of type struct Pair and assign 3 and 5 to
members x and y:
struct Pair pr; pr.x = 3; pr.y = 5;
-
Declare an array of struct Pair elements and assign the integer
pair 3 and 5 to the first element of the array.
struct Pair pairs[20]; pairs[0].x = 3; pairs[0].y = 5;
-
Declare a struct Pair variable with values 3 and 5. Then
declare a pointer to a struct Pair and assign the address of
the of the struct Pair to the pointer. Use the pointer to add
the pair of integers and assign the sum to an integer variable.
struct Pair pr; struct Pair *sp; int sum; pr.x = 3; pr.y = 5; sp = ≺ sum = sp->x + sp->y; // same as sum = pr.x + pr.y;
-
Declare a function listPairs that takes two parameters: an array of struct
Pair type and an integer.
void listPairs(struct Pair prs[], int n);
When passing an array, the actual value passed is the address of the first element.
So an equivalent declaration for listPairs is:
void listPairs(struct Pair *prs, int n);
-
Call the function listPairs, passing the array named pairs
from (3) above and 20 as the integer array size:
listPairs(pairs, 20);
-
Declare a function, maxPair, that returns a pointer to a
struct Pair. Its parameters should be a struct Pair array and
an integer.
struct Pair * maxPair(struct Pair prs[], int n);
or equivalently
struct Pair * maxPair(struct Pair *prs, int n);
-
Write statemetns to call maxPair and print the two integers
in the struct Pair it returns.
struct Pair *sp; sp = maxPair(pairs, 20); printf("(%d, %d)\n", sp->x, sp->y);