From the course: Master C Language Pointers

Understanding pointers - C Tutorial

From the course: Master C Language Pointers

Start my 1-month free trial

Understanding pointers

- [Narrator] A pointer is a variable that holds a memory location, an address. Specifically it's the address of another variable in the program. Or it could be the address of a chunk of memory, an array or a buffer. But why? Well part of the answer is that C is a midlevel language. In a way it's almost shorthand for assembly language which is close to the machine code spoken directly by the processor. C's pointers provide access to memory locations similar to the way assembly language accesses memory directly. Pointers offer a potent way to examine and manipulate data. Because of their low level access, using pointers involves a few rules. First, a pointer is declared as a specific data type. The type matches the data the pointer must reference. So to obtain the address of a character variable, a character pointer is used. Second and most importantly, a pointer must be initialized before it's used. This rule is true for all C language variables but more so for pointers. That's because an uninitialized pointer contains an unknown memory location which if accessed can crash the program or bring down the entire system. The final and most confusing aspect of pointers is their dual nature. You use the unary asterisk operator to declare a pointer, like this. After it's declared and initialized of course, the pointer is used with or without the asterisk operator. Without the asterisk operator, the pointer refers to an address. With the asterisk, it refers to the value stored at the address. This exercise file shows both usages as well as a few important aspects of a pointer. So pointer ptr is declared at line six. It uses the asterisk. It's initialized down at line 13. Specifically, it's initialized to the address of variable a which is assigned a value here at line nine. The pointer's address which is the address of variable a is output at line 14 thanks to the %p placeholder here. And the pointer variable is used without the asterisk. At line 15 however, the pointer variable is used with the asterisk to output the value of variable a's address. You see it's a character by this placeholder and the value would be the uppercase letter A. Let's see how this builds and runs. And here you see the address of variable a which is going to be different from system to system. But the value stored at that address is the letter A which is the value of variable a. Of course there's more to pointers than this simple example. But the code presents the basics, a foundation upon which you can build your pointer knowledge.

Contents