Videos
I see a lot of people using pointers/references instead of a actual variable. I know that pointers are variables that store the memory location of a already existing variable and that references are not stored in memory because they "reference" to a variable (and because of that, it can't change to what it references on later).
I can think only 2 cases where pointers/references are useful:
-
Because I can't
returnanarray, when I want toreturnone, I can return areferenceto it. -
To avoid
variable-duplication.
Apart from this, I can't think why should I want to use them.
Did I understand something wrong?
One benefit of pointers is when you use them in function arguments, you don't need to copy large chunks of memory around, and you can also change the state by dereferencing the pointer.
For example, you may have a huge struct MyStruct, and you have a function a().
void a (struct MyStruct* b) {
// You didn't copy the whole `b` around, just passed a pointer.
}
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.)