We have seen structs that contains pointers, arrays that contain structs, but we haven't quite seen points to structs. A pointer to a struct is essentially what we think of as an object reference in languages like Java. These are so important in C that there is special syntax for it. We are about to reimplement our repo with an array of pointers to wordEntry objects, but first a little background. You will also want to review K&R chapter 6.
Let's take our old friend point from the last lab.
struct point { int row; int column; };We can statically allocate one with.
struct point origin ;We can statically allocate one and initialize it with
struct point origin = {0,0};We can refer to its elements as
origin.row
We can declare a pointer to one of these with
struct point *p;We could even assign p to point to origin with
p = &origin;And we could reference its fields either using the combination
*p.rowOr we could use the special arrow syntax.
p->rowSo how would we dynamically allocate a point? Easy malloc. And we get its size either from an object of this type or the type inself.
p = malloc(sizeof(struct point));And now we can fill in its fields. Here's a little example.
#include <stdlib.h> #include <stdio.h> struct point { int row; int column; }; int main(int argc, char *argv[]) { int x = (argc > 1) ? atoi(argv[1]) : 0; int y = (argc > 2) ? atoi(argv[2]) : 0; int dist; struct point origin = {0,0}; struct point *p; printf("Manhantan distance from (0,0) to (%d,%d) is ", x, y); p = malloc(sizeof(struct point)); p->row = x; p->column = y; dist = (p->row - origin.row) + (p->column - origin.column); printf("%d",dist); free(p); printf("\n"); return 0; }Paste it into a file and try it oout.