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¶
True/False: The correct way of declaring a character array is
char[] array.
Solution
False. The correct way is char array[].
True/False: C is a pass-by-value language.
Solution
True. If you want to pass a reference to anything, you should use a pointer.
What is a pointer? What does it have in common with an array variable?
Solution
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?).
If you try to dereference a variable that is not a pointer, what will happen? What about when you free one?
Solution
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.