1And in Conclusion¶
C pointers and arrays are pretty much the same[1], except with function calls.
C knows how to increment pointers.
C is an efficient language, but with little protection:
Array bounds not checked
Variables not automatically initialized
Use handles to change pointers.
Strings are arrays of characters with a null terminator. The length is the # of characters, but memory needs 1 more for \0
Beware: The cost of efficiency is more overhead for the programmer. “C gives you a lot of extra rope, don’t hang yourself with it!”
2Textbook Reading¶
K&R: Chapters 5-6
3Additional References¶
Professor Emeritus Brian Harvey’s notes on C
4Exercises¶
Check your knowledge!
4.1Conceptual Review¶
Solution to Exercise 1 #
False. The correct way is char array[].
Solution to Exercise 2 #
True. If you want to pass a reference to anything, you should use a pointer.
Solution to Exercise 3 #
As we like to say, “everything is just bits.” A pointer is just a sequence of bits, interpreted as a memory address. An array acts like a pointer to the first element in the allocated memory for that array. However, an array name is not a variable, that is, &arr = arr whereas &ptr != ptr unless some magic happens (what does that mean?).
Solution to Exercise 4 #
It will treat that variable’s underlying bits as if they were a pointer and attempt to access the data there. C will allow you to do almost anything you want, though if you attempt to access an “illegal” memory address, it will segfault for reasons we will learn later in the course. It’s why C is not considered “memory safe”: you can shoot yourself in the foot if you’re not careful. If you free a variable that either has been freed before or was not malloced/calloced/realloced, bad things happen. The behavior is undefined and terminates execution, resulting in an “invalid free” error.
The biggest difference between arrays and pointers comes down to where they are located in memory; this difference leads to the many details you saw in this chapter. See the next chapter for an overarching framework of memory layout that will help you understand the distinction.