CSE 100 Lecture Notes - Lecture 43: Memory Management, Memory Leak, Bounds Checking
Chapter 10
● Each variable in a program is stored at a unique location in memory that has an
address
● Use the address operator & to get the address of a variable
○ Int num = -23;
○ Cout << # //prints address in hexadecimal
○ The address of a memory location is a pointer
● Point Variable (pointer): a variable that holds an address
● Pointers provide an alternative way to access memory locations
● Definition
○ Int *intptr;
● Read as
○ Intptr can hold the address of an int or the variable that intptr points to has
type int
○ The Spacing in the definition does not matter:
■ Int * intptr;
■ int*intptr;
■ *is called the indirection operator
● Definition and assignment
○ int num = 25;
○ int*intptr;
○ intptr = #
● Memory layout
● You can access num using intptr and indirection operator *:
● cout << intptr;
● cout << *intptr;
● *intptr = 20;
● An array name is the starting address of the array
● Relationship Between Arrays and Pointers
○ An array name can be used as a pointer constant
○ A pointer can be used as an array name
● Pointers in Expressions
○ Given:
■ int vals[] = {4,7,11};
■ int *valptr = vals;
○ What is valptr + 1?
○ It means (address in valptr) + (1*size of an int)
Document Summary
Each variable in a program is stored at a unique location in memory that has an address. Use the address operator & to get the address of a variable. Cout << # //prints address in hexadecimal. The address of a memory location is a pointer. Point variable (pointer): a variable that holds an address. Pointers provide an alternative way to access memory locations. Intptr can hold the address of an int or the variable that intptr points to has type int. The spacing in the definition does not matter: You can access num using intptr and indirection operator *: An array name is the starting address of the array. An array name can be used as a pointer constant. A pointer can be used as an array name. It means (address in valptr) + (1*size of an int) Array elements can be accessed in many ways. Remember that no bounds checking is performed on array access.