Which book are you reading? It seems strange that your book wouldn't teach you something like this...
The idea of pointers is that they allow functions such as scanf
to assign to an object they point at (hence the name, pointers tend to point at things). Like other variables, however, you need to initialise them!
Suppose you have a function add_one
which adds to its argument:
void add_one(int x) {
x++;
}
This function is useless as the changes it makes to x
aren't visible to the caller, due to a concept known as pass-by-value where copies of the values passed in are made, which end up being what gets modified (and so the original remains the same).
You need to make x
a pointer to make that change visible outside of add_one
, and the same change was necessary for scanf
.
void add_one(int *x) {
(*x)++; // equivalent to x[0]++;
}
Of course, this won't work if x
doesn't actually point to something! In your example, you've got uninitialised pointer variables; they're pointing at... nothing? anything? who cares? Make them point somewhere!
You can do this by:
Using the &
address-of operator on a variable. For example:
int x;
int *pointer_to_x = &x;
Declaring an array, and using the identifier of the array, possibly in conjunction with the +
addition operator to point at an element in the array. For example:
int array[42];
int *pointer_to_first = array + 0;
int *pointer_to_second = array + 1;
Calling malloc
, realloc
, calloc
or some other function that returns a pointer to a suitably sized object. For example:
int *pointer_to_whatever = malloc(sizeof *pointer_to_whatever);
// Remember to free(pointer_to_whatever) ONCE when you're done with it