ottomobiehl wrote:
Pointers are my first hurdle. I think I understand what they are and what they do but not really what to use them for.
To declare a pointer I do this:
int *i;
right?
so if I do:
int x = 5;
int *i;
i = &x;
then i will equal the memory address of x but not the value of x, right?
Correct, but unexciting. To get the value of x from the pointer you dereference the pointer thus:
e.g.
int a;
a = *i;
The '*' dereferences the pointer to give the value of what is pointed at. The value of what is pointed at can also be changed thus:
*i = 5;
Which puts 5 at the address pointed to by i.
However, imagine you have a nice big number of things you wished to pass around, like maybe a person and you wished to pass that person (or persons like it) to a collection of functions. Let's say a person has a number of attributes like:
height, weight, dayOfBirth, monthOfBirth, yearOfBirth, name, sex
Each time you wanted to pass all that stuff to a function the call would be tedious indeed.
Instead you can create a structure and just pass a pointer to the structure a la:
typedef struct {
int height;
int weight;
int dayOfBirth;
int monthOfBirth;
int yearOfBirth;
char * name;
char sex;
} personT;
Note that name is a pointer to the start of a string of bytes.
The personT is now a type (like int or char) that you can use to declare variables as. Then you can set the values.
personT mrX;
mrX.height = 167;
mrX.weight = 70;
mrX.dayOfBirth = 5;
mrX.monthOfBirth = 6;
mrX.yearOfBirth = 1978;
mrX.name = "Fred X";
mrX.sex = 'M';
/* and now you can call a function that does something with persons */
printBirthday(&mrX);
and printBirthday would look something like...
void printBirthday(personT * person)
{
printf("%s was born %d/%d/%d\n",
person->name,
person->dayOfBirth,
person->monthOfBirth,
person->yearOfBirth );
}
Note that when you are accessing members of a struct, use . (dot). When you are accessing members of a pointer to a struct use -> (arrow or points-to).