I recently developed an interest in C programming so I got myself a book (K&R) and started studying.
Coming from a University course in Java (basics), pointers a
Coming from Java, you'll have a slightly different perspective than what is presented in K&R (K&R doesn't assume that the reader knows any other modern programming language).
A pointer in C is like a slightly more capable version of a reference in Java. You can see this similarity through the Java exception named NullPointerException
. One important aspect of pointers in C is that you can change what they point to by increment and decrement.
In C, you can store a bunch of things in memory in an array, and you know that they are sitting side by side each other in memory. If you have a pointer to one of them, you can make that pointer point to the "next" one by incrementing it. For example:
int a[5];
int *p = a; // make p point to a[0]
for (int i = 0; i < 5; i++) {
printf("element %d is %d\n", i, *p);
p++; // make `p` point to the next element
}
The above code uses the pointer p
to point to each successive element in the array a
in sequence, and prints them out.
(Note: The above code is an expository example only, and you wouldn't usually write a simple loop that way. It would be easier to access the elements of the array as a[i]
, and not use a pointer there.)