How Do Pointers Work in C and C++?

5.7M views
•
December 29, 2020
by
freeCodeCamp.org
YouTube video player
How Do Pointers Work in C and C++?

TL;DR

A pointer is a variable that stores the address of another variable. Declare one by putting an asterisk before the name (int *p), get an address with the ampersand operator (p = &a), and read or write the value at that address by dereferencing with the asterisk (*p = 8). Using a pointer before initializing it crashes the program.

Transcript

The course you're about to watch is about pointers  in C. The course was developed by the excellent instructors from my code school. My Code School is  one of the earliest software channels on YouTube, and has inspired many developers and creators.  In the description. I've included a link to an article about the channels amazing story.  Now let's ... Read More

Key Insights

  • A pointer is a variable that stores the address of another variable, and because the pointer itself lives in memory, it also has its own address that can be printed with the ampersand operator.
  • Every byte of RAM has an address, and when a variable is declared the computer allocates bytes starting at one address and records the variable's name, type, and starting address in an internal lookup table.
  • How much memory a variable takes depends on the data type and the compiler: in a typical modern compiler an integer gets four bytes, a float gets four bytes, and a character gets one byte.
  • Assignment works through the lookup table: when the machine sees a = 5, it looks up variable a, finds its type and starting address, then writes the value into the bytes at that address in binary form.
  • The pointer declaration syntax is the data type followed by an asterisk and the variable name, so int *p declares a pointer to integer and char *p0 declares a pointer to character.
  • The ampersand operator placed in front of a variable returns the address of that variable, in fact returning a pointer to it, which is how a statement like p = &a fills the pointer.
  • Dereferencing means putting an asterisk in front of a pointer to get the value stored at the address it holds, so if p points to a and a is 5, then printing *p outputs 5.
  • Dereferencing also writes: a statement like *p = 8 modifies the value at the address stored in p, so printing either *p or a afterwards outputs 8.
  • A pointer can be reassigned to point elsewhere, so if p holds address 204 for variable a and is changed to 208 where variable b lives, p then points to b instead.
  • Pointer types must match what they point to: an integer pointer is needed to store the address of an integer, a character pointer for a character, and pointers can also target doubles or user-defined structures and classes.

Install to Summarize YouTube Videos and Get Transcripts

Explore YouTube Video Summarizer or Get YouTube Transcript Extractor

Questions & Answers

Q: What is a pointer in C and C++?

A pointer is a variable that stores the address of another variable. Ordinary variables hold values such as an integer or a character, but a pointer holds the memory location where another variable lives. Because a pointer holds an address, you can use operators on it to reach the variable it points to and both read and modify that variable's value. A pointer is itself a variable stored in memory, so it occupies its own bytes at its own address, and it can be changed later to point at a different variable of the same type.

Q: How do you declare a pointer variable in C?

You declare a pointer by writing the data type, then an asterisk, then the variable name. Writing int *p declares p as a pointer to an integer, meaning p can store the address of an integer variable. The same pattern applies to other types: char *p0 declares a pointer to a character, and you can likewise declare a pointer to double. Pointers can also point to a user-defined structure or a user-defined class. The type matters because a pointer to an integer is what you need to store the address of an integer, and a character pointer is what you need for a character variable.

Q: What does the ampersand operator do in C?

Putting an ampersand in front of a variable gives you the address of that variable. It acts as an operator that returns a pointer to that particular variable, which is why the statement p = &a stores the address of a into the pointer p. If variable a is allocated at address 204, then printing &a outputs 204, exactly the same as printing the pointer p after that assignment. The ampersand works on any variable, including a pointer itself: since p is also a variable stored in memory, printing &p gives p's own address, for example 64.

Q: How do you get the value stored at a pointer's address?

You put an asterisk sign in front of the pointer, which gives the value at the location it points to. This is called dereferencing, because a reference or address has been stored in the pointer and the operator retrieves the value living at that address. If p holds the address of a and a is 5, then printing *p outputs 5. The distinction to remember is that p by itself is the address, while *p is the value at the address stored in p, so printing a pointer without the asterisk shows an address rather than data.

Q: Can you change a variable's value through a pointer?

Yes. Dereferencing works for writing as well as reading, so a statement such as *p = 8 modifies the value stored at the location the pointer points to. If p holds the address of variable a, then after *p = 8 both printing *p and printing a output 8, because they refer to the same four bytes of memory. This is the core reason pointers are powerful: code that holds only the address of a variable can still update the original variable, without needing the variable's own name in scope.

Q: Why does printing an uninitialized pointer crash a C program?

In the demonstration, an integer variable a and a pointer to integer p are declared, and then p is printed straight away without ever being assigned. Running that program produces an error stating that the variable p is not initialized and is being used without initialization, and the program crashes. The fix shown is to add the statement p = &a, which is nothing but the address of a, before using p. Once p holds a real address, the program runs. The lesson is that a pointer must be pointed at something valid before it is used.

Q: How much memory does a variable take in C?

How much memory the computer allocates depends on the data type and also on the compiler. In a typical modern day compiler an integer is allocated four bytes of memory, a float is allocated four bytes, and a character variable is allocated one byte. When the machine sees a declaration such as int a during execution, it knows four bytes are needed, finds free space, and records the starting address. In the walkthrough, integer a occupies the four bytes beginning at address 204, while character c takes the single byte at address 209.

Q: How does a computer keep track of where variables are stored?

The computer maintains an internal structure called a lookup table. When a variable is declared, the machine allocates the required bytes and records an entry saying that the variable exists, what type it is, and what its starting address is, for example that a is an integer located at address 204. Whenever the program then performs an operation on that variable, such as assigning 5 or incrementing it, the machine looks the variable up in that table, goes to the recorded address, and reads or modifies the value stored in those bytes.

Summary & Key Takeaways

  • Memory is the foundation of pointers. RAM is divided into bytes, each with its own address that increases as you move up. Declaring int a makes the computer allocate four bytes, say starting at address 204, and record in a lookup table that a is an integer stored at 204. A character variable c takes just one byte, for example at address 209.

  • Operations on variables go through that lookup table. When the program runs a = 5, the machine finds a's entry, goes to address 204, and writes 5 into those four bytes in binary. An increment statement later repeats the lookup and changes the stored value to 6. Pointers exist so the program itself can read and operate on these addresses.

  • The syntax has two operators. An asterisk in the declaration makes a pointer variable, as in int *p, meaning p can hold the address of an integer. An ampersand in front of a variable yields its address, so p = &a stores a's address in p. Printing p or &a both give 204, while &p gives p's own address, 64.

  • Dereferencing retrieves and changes the pointed-to value. Printing *p when a is 5 outputs 5, and writing *p = 8 changes a itself to 8. The rule to remember is that p without the asterisk is the address, and *p with the asterisk is the value at that address.

  • Errors and further topics follow. In a live demo, declaring int *p and printing it without assignment produces an error that the variable is not initialized and the program crashes; adding p = &a fixes it. Later lessons cover pointer arithmetic, void pointers, pointers to pointers, call by reference, arrays, dynamic memory, and function pointers.


Read in Other Languages (beta)

Share This Summary 📚

Explore More Summaries from freeCodeCamp.org 📚