# Pointers chp 10 Dynamic Memory Allocation chp 16

• Slides: 34

Pointers (chp 10) Dynamic Memory Allocation (chp 16, pg 384) Command-Line Arguments (chp 16, pgs 380 -384) 1

Pointer Variable § A variable that stores a memory address �Allows C programs to simulate call-byreference �Allows a programmer to create and manipulate dynamic data structures § Must be defined before it can be used �Should be initialized to NULL or valid address 2

Declaring Pointers Declaration of pointers <type> *variable = initial-value Examples: 3

Pointers A pointer variable has two associated values: § § Direct value § § § Indirect value § § 4 address of another memory cell Referenced by using the variable name value of the memory cell whose address is the pointer's direct value. Referenced by using the indirection operator *

Pointer Operators Come before a variable name § � Ø Ø 5 * operator Indirection operator or dereferencing operator Returns a synonym, alias or nickname to which its operand points & operator Address of operator Returns the address of its operand

Pointer Variables § One way to store a value in a pointer variable is to use the & operator �The address of count is stored in count. Ptr �We say, count. Ptr points to count 6

Pointer Variables § Assume count will be stored in memory at location 700 and count. Ptr will be stored at location 300 � causes 5 to be stored in count � causes the address of count to be stored in count. Ptr 7

Pointer Variables We represent this graphically as 8

Pointer Variables § The indirection / dereferencing operator is * � stores the value 10 in the address pointed to by count. Ptr 9

Pointer Variables § The character * is used in two ways: 1. To declare that a variable is a pointer Ø Pre-pending a variable with a * in a declaration declares that the variable will be a pointer to the indicated type instead of a regular variable of that type 2. To access the location pointed to by a pointer Ø Pre-pending a variable with a * in an expression indicates the value in the location pointed to by the address stored in the variable 10

Simulating By Reference § Invoked function uses * in formal parameters § Invoking function (function call) uses & in arguments 11

Pointer Variables § Given �The compiler will know how many bytes to copy into the memory location pointed to by a. Ptr 12

Pointer Variables and Arrays § Given �Notice that a. Ptr is assigned to a and not &a – why? ? �What happens after the third line of code above? ? 13

Arrays Sent to Functions § Consider an array declaration: § which would result in a block in memory consisting of ten integers (of 4 bytes in a row per integer). § Let’s say this array begins at memory location 10010 - we may imagine it looks like this in memory: § Example of sorting function with this array sent in as an argument: 14

Pointer Variables and Arrays § Same array as last slide: § Assume we also declare an integer pointer to point to the array: (What is another way to write this? ) § Then we can imagine it looking like this: § What does the following mean: *(a. Ptr + 1) § Which is the same as writing what? ? 15

Pointer Variables and Arrays § Since a block of 10 integers located contiguously in memory is, by definition, an array of integers, this brings up an interesting relationship between arrays and pointers: § After declaring an integer pointer to point to the array, or like this: we can access the elements in the array using: � array subscript notation, like we are used to a[3] � or using the pointer *(a. Ptr + 3) 16

Pointer Variables and Arrays § Same array: § What happens with the following statement? a. Ptr = a. Ptr + 1; 17

Pointer Variables and Arrays § Because the compiler "knows" �This is a pointer (i. e. its value is an address) �That it points to an integer of length 4 at location 100 § Instead of 1, a. Ptr = a. Ptr + 1; adds 4 to a. Ptr �Now a. Ptr "points to" the next integer at location 104 �Same for: a. Ptr += 1, a. Ptr++, and ++a. Ptr 18

Pointer Variables and Arrays § Consider this array allocated at location 200 �We have an array containing 10 integers � We refer to each of these integers by means of a subscript to scores Ø Using scores[0] through scores[9] 19

Pointer Variables and Arrays § The name of an array and the address of the first element in the array represent the same thing § Consequently, we could alternatively access them via a pointer: 20

Pointer Variables and Arrays § The name of an array is a pointer constant to the first element of the array § So, we could also use : 21

Pointer Arithmetic and Arrays § If score. Ptr is pointing to a specific element in the array and n is an integer, score. Ptr + n is the pointer value n elements away § We can access elements of the array either using the array notation or pointer notation �If score. Ptr points to the first element, the following two expressions are equivalent: scores[n] *(score. Ptr + n) 22 Array notation Pointer notation

Pointers and Dynamic Allocation of Memory § So far, we have always allocated memory for regular variables that are located on the stack �Size of such variables must be known at compile time § Sometimes convenient to allocate memory at run time �System maintains a second storage area called the heap �Functions calloc and mallocate memory as needed of size needed 23

Pointers and Dynamic Allocation of Memory 1. Use allocating function (such as malloc(), calloc(), etc. ) �Returns void pointer Ø void * indicates a pointer to untyped memory Ø Will have to cast the returned value to the specific type needed 2. Use memory through the pointer notation 3. Release allocated space when no longer needed, so that it can be reused 24

Pointers and Dynamic Allocation of Memory: calloc § calloc �Used to dynamically create an array in the heap �Contiguous allocation Ø Initialized to binary zeros �Must �Takes two arguments 1. Number of array elements 2. Amount of memory required for one element � Use sizeof operator �Returns Ø Void pointer if successful Ø NULL if unsuccessful 25

Pointers and Dynamic Allocation of Memory: calloc § Example 1: String § Example 2: Integers 26

Pointers and Dynamic Allocation of Memory: malloc § malloc �Used to dynamically get memory from heap �Contiguous allocation Ø No initialization �Must �Takes one argument Ø Total amount of memory required �Returns Ø Void pointer if successful Ø NULL if unsuccessful 27

Pointers and Dynamic Allocation of Memory: malloc § Example 1: String § Example 2: Integers 28

Pointers and Dynamic Allocation of Memory: free § free �Used to dynamically release memory back to heap �Contiguous deallocation �Must �Takes one argument Ø Pointer to beginning of allocated memory �Good idea to also NULL pointer if reusing 29

Pointers and Dynamic Allocation of Memory: free § Example 2 with free 30

Command-Line Arguments § Arguments passed to a program upon execution are called command-line arguments. § The main() function signature changes from int main(void) to int main(int argc, char *argv[]) § The first argument argc holds the number of items types at the command prompt, including the executable name. § The second argument char *argv[] is an array of character pointers, each pointer pointing to the arguments typed in at the command-line. 31

Command-Line Arguments § With the reverse_echo program, if you type . /a. out testing 1 2 3 at the command-prompt, argc would have the value 5, and argv[] would look like this: 32

sscanf() § We have used scanf() to scan input from the keyboard. § sscanf() scans an array (or string) already in memory and reads each item into a pointer that points to the address (just like scanf()) int sscanf( buffer, format(s), arg(s) ) where buffer is the given array, or string (the source) format is the format specifier (%d, %f, %s, etc) arg is the pointer(s) to the address of each argument (destinations) 33

sscanf() § Example 1: int number. Of. Args = 0; number. Of. Args = sscanf(my. Int. Array, %d, %d, &num 1, &num 2, &num 3); § Example 2: if sample run is . /a. out John 7 12 printf(“Hello %s. n”, argv[1]); sscanf(argv[2], “%d”, &birth. Month); sscanf(argv[3], “%d”, &birth. Day); 34