Memory Pointers Pointers 101 pointer memory address of

  • Slides: 32
Download presentation
Memory & Pointers

Memory & Pointers

Pointers 101 • pointer: memory address of a piece of data • Why pointers?

Pointers 101 • pointer: memory address of a piece of data • Why pointers? • • Address can be used to access/modify the data from any function Pass a pointer to the data instead of a whole copy of the data Pointers required for file I/O Used in many data structures, e. g. , linked lists • Two operators which are opposites • address-of operator &: memory address of data • indirection (contents at) operator *: data stored at an address • also used to declare a pointer variable

Pointers • Store memory addresses in pointer variables int i = 3; int *i.

Pointers • Store memory addresses in pointer variables int i = 3; int *i. Ptr = &i; // address of i // *i. Ptr: value that i. Ptr points to i. Ptr 0 x 7 fff • Can use pointer to change contents at memory location • *i. Ptr = 5; // same result as i = 5; • printf("Value of i: %dn", i); • Output: Value at i: 5 • Note the uses of *i. Ptr above: • Declaration: int *i. Ptr: i. Ptr points at an int • Dereferencing (accessing contents at): *i. Ptr = 5; i 3 Addr: 0 x 7 fff

More on Pointers int number = 23; *p 1, *p 2; p 1 =

More on Pointers int number = 23; *p 1, *p 2; p 1 = &number; p 2 = &number; printf ("*p 1 = %d What’s the Output ? number 23 p 1 p 2 *p 2 = %d ", (*p 1), (*p 2));

Pointer Arithmetic int arr[] = {3, 1, 8, 7}; int *p = arr; //

Pointer Arithmetic int arr[] = {3, 1, 8, 7}; int *p = arr; // p points to arr[0] • p + i points to arr[i] • arr + i points to arr[i] • Address value increases by i * sizeof(int) • *(arr + 1) is 1 • *(arr + 2) is 8

Pointer Arithmetic • Only addition, subtraction and comparison operations are allowed for pointer variables

Pointer Arithmetic • Only addition, subtraction and comparison operations are allowed for pointer variables • Array name is pointer to first element of array • Pointer arithmetic is done relative to the base type int *p =NULL, *q =NULL; int x[4] = {25, 37, 77, 99}; p = &x[0]; // OR just p = x; q = p; q++; // advances by sizeof(int) bytes, *q is 37 printf (“value is %d”, *(q + 2)); // value is 99 • A pointer can be used to iterate through an array/string char str[] = "Test"; char *p; int i; for( p = str, i=0; *p != ''; p++, i++) printf("The character at position %d is %cn ", i, *p );

Pointers and Arrays char str[80] = "hello"; char *ptr; ptr = str; // ptr

Pointers and Arrays char str[80] = "hello"; char *ptr; ptr = str; // ptr = &str[0] strcpy(ptr, "test"); str ptr 0 int arr[8]; int *ptr = arr; arr[3] = 84; *(ptr+4) = 94; 1 2 t e s t 3 4 5 6 7 84 94 arr ptr (ptr + 4) . . .

Pointers and Arrays #define NUM_ELTS 100 int a[NUM_ELTS], *p; // assume elements of a

Pointers and Arrays #define NUM_ELTS 100 int a[NUM_ELTS], *p; // assume elements of a are assigned values. . . int sum = 0; for(p = a; p < a + NUM_ELTS; p++) sum = sum + (*p); printf("Sum = %dn", sum);

Accessing String Characters – 2 Ways • Because of the close relationship between arrays

Accessing String Characters – 2 Ways • Because of the close relationship between arrays and pointers, strings can be accessed either by array subscripting or by pointer reference. • function that counts the number of spaces in a string: Pointer version : int count. Spaces(const char s[]){ int count, i; count = 0; for (i = 0; s[i] != ''; i++){ if (s[i] == ' ') count++; } return count; } int count. Spaces(const char *s) { char *p; int count; count = 0; for (p = s; *p != ''; p++){ if (*p == ' ') count++; } return count; } char str[] = “now is the time for all good men to come to the aid of their country. ”; printf(“the number of spaces are: %d”, count. Spaces(str));

swap function • Write a function to swap two integers void swap(int x, int

swap function • Write a function to swap two integers void swap(int x, int y) { int temp = x; x = y; y = temp; } x 5 3 y 3 5 Ouput: one: 5, two: 3 After swap: one: 5, two: 3 Why doesn't this work? int main() { int one = 5; int two = 3; printf("one: %d, two: %dn", one, two); swap(one, two); printf("After swap: "); printf("one: %d, two: %dn", one, two); } 5 one 3 two

C: Pass By Value • When a function is called, the value of argument

C: Pass By Value • When a function is called, the value of argument is copied into the corresponding parameter of the function. • The called function foo cannot change the value of the argument, p int foo(int n) { n = 7; printf("n = %dn", n); // 7 } void caller. Of. Foo() { int p = 30; foo(p); // the value of p copied into foo's param n printf("p = %dn", p); // 30 } • Workaround: you could pass a pointer to a variable instead • Then the pointer cannot be modified by the function, but the data it points to can be

C: Pass By Value • When a function is called, the value of argument

C: Pass By Value • When a function is called, the value of argument is copied into the corresponding parameter of the function. • Pass an argument's address to allow other function to modify arg's value void caller. Of. Foo() { int p = 30; foo(&p); // copy address of p into n printf("p = %dn", p); // 7 int foo(int *n) { *n = 7; printf("*n = %dn", *n); // 7 } Output when caller. Of. Foo() is invoked: *n = 7 p = 7 } n p 30 7

Accessing Caller's Variables • Write a function to swap two integers void swap(int *px,

Accessing Caller's Variables • Write a function to swap two integers void swap(int *px, int *py) { int temp = *px; *px = *py; *py = temp; } Output: one: 5, two: 3 After swap: one: 3, two: 5 int main() { int one = 5; int two = 3; printf("one: %d, two: %dn", one, two); swap(&one, &two); printf("After swap: "); printf("one: %d, two: %dn", one, two); }

Example: What's Wrong? #include<stdio. h> char *get. Message() { char msg[] = "Pointers are

Example: What's Wrong? #include<stdio. h> char *get. Message() { char msg[] = "Pointers are fun!"; return msg; } int main() { char *string = get. Message(); puts(string); }

Memory • How is memory organized? • text = code • data = constants,

Memory • How is memory organized? • text = code • data = constants, initialized global/static variables • bss = uninitialized global, static variables • stack = local variables • heap = dynamic memory • malloc'ed memory • The runtime (or call) stack used by a process (running program) to keep track of function calls https: //en. wikipedia. org/wiki/File: Program_memory_layout. pdf

What is a Stack? • stack: abstract data type that represents a collection of

What is a Stack? • stack: abstract data type that represents a collection of elements • access only allowed at one point of the structure, typically called the top of the stack • access to the most recently added item only • like a stack of plates in a cafeteria – last in, first out (LIFO) • new elements/plates placed on top • the top plate/element is always the first to be removed • Fundamental operations • • push: add item to stack pop: remove top item from stack top: get top item without removing it is. Empty https: //en. wikipedia. org/wiki/Stack_(abstract_data_type)

Call Stack • area of computer memory for local variables • when a function

Call Stack • area of computer memory for local variables • when a function is called: a stack frame or activation record is pushed onto the call stack • AR contains local variables, parameters, return address back to function's caller • when a function's execution ends: its activation record is popped off the stack • stack pointer points to current (topmost) stack frame, which contains data for function currently being executed • Note that the call stack is upside down, i. e. , grows downward

Memory int SIZE = 3; int foo() { static char *s; static char *str

Memory int SIZE = 3; int foo() { static char *s; static char *str = "these are not the droids you're looking for"; int num = 5; char *p = malloc(10*sizeof(char)); } https: //en. wikipedia. org/wiki/File: Program_memory_layout. pdf

Pointer & Memory Recap • Local variables live on the stack in their function's

Pointer & Memory Recap • Local variables live on the stack in their function's stack frame during function execution • Use & operator to get address of a variable • Use * operator to get the contents at a memory address • Pointers are variables that store memory addresses

Arrays, Strings and Pointers

Arrays, Strings and Pointers

Arrays • In C, arrays are known by their address int arr[5]; 1008 1004

Arrays • In C, arrays are known by their address int arr[5]; 1008 1004 1000 arr[2] = 3; 1012 3 1000 + 2*sizeof(int) = 1000 + 2*4 = 1008 arr[7] = 40; 1000 + 8*4 = 1032 1016 1032 40

Passing Arrays • When you pass an array to a function, the array name

Passing Arrays • When you pass an array to a function, the array name is treated as a pointer– it's just the address of the 1 st array element void array. Fn(int a[]) { int main() { // sizeof returns bytes for int pointer int arr[] = {3, 1, 9, 0, 2}; printf("sizeof arr: %zun", sizeof(arr)); printf("sizeof a: %zun", sizeof(a)); array. Fn(arr); } } Output: sizeof arr: 20 sizeof a: 8 • Could change the first line of function to: void array. Fn(int *a) {. . .

Array Variables: Not Quite Pointers. . . How are they different? • char s[]

Array Variables: Not Quite Pointers. . . How are they different? • char s[] = "hello world"; char *t = s; • sizeof(s): the size of the array in bytes (12) sizeof: different • sizeof(t): size of a pointer (8 probably) • An array variable cannot be reassigned to point to something else. • array variable doesn't have allocated storage // compiler error • Pointer vs. Array: string modification s = t; • char *p = "hello"; vs. char a[] = "hello"; • p cannot be used to modify the string literal; a can modify the array • String literals are in read only memory: p[0] = 'c'; // nope • Declare a char pointer as const char * to prevent where they can point: different!

Array Arguments • Write a function that computes and returns the sum of an

Array Arguments • Write a function that computes and returns the sum of an int array's elements. Use pointer arithmetic to iterate over the array. • Note: You will need to pass the array as well as the array's length.

char arrays vs. char pointers • String literals cannot be modified • char *card

char arrays vs. char pointers • String literals cannot be modified • char *card = "KH"; // cannot be modified • string literal "KH" cannot be changed • card contains address of string literal "KH" • char card[] = "KH"; // can modify the array • array contains a copy of the literal "KH" • char *card = "KH"; • Trying to modify the string that card points to can cause unpredicatable results • Instead use: const char *card = "KH"; • card is a pointer to a const char • compiler will produce an error if you attempt to modify the string • Ex: card[0] = 'J'; // compilation error

Pointer Return Values • Recall: Don't return pointer to local variable • Can return

Pointer Return Values • Recall: Don't return pointer to local variable • Can return pointer to a global or static variable, or an element of an array parameter int *find. Middle(int a[], int n){ return &a[n/2]; } int *max(int *a, int *b) { if(*a > *b) return a; else return b; } Function call: Returns address of i or j int *largest, i = 5, j = 4; largest = max(&i, &j);

Pointer Arguments • You can use pointer arguments when you want a function to

Pointer Arguments • You can use pointer arguments when you want a function to "return" 2 or more values • Ex: scanf() int a, b; scanf("%d %d", &a, &b); • Not: int a = scanf(. . . );

Exercise • Write a function that finds the min and max values in an

Exercise • Write a function that finds the min and max values in an int array. // pre: a != NULL and length of a is positive void max. Min(int *a, int len, int *min. Ptr, int *max. Ptr) {. . . } int main() { int arr[] = {1, 6, 2, 4, -7, 9}; int small, large; max. Min(arr, sizeof(arr)/sizeof(arr[0]), &small, &large); printf("Min = %dn", small); printf("Max = %dn", large); }

structs & pointers

structs & pointers

struct pointers • structs are copied element wise – for large structs, more efficient

struct pointers • structs are copied element wise – for large structs, more efficient to pass pointer • struct pointer can access fields with struct point { int x; int y; }; struct point p = {5, 9}; struct point *p. Ptr = &p; p. Ptr x = 3; // changes p. x int y = p. Ptr y; // same as y = p. y (*p. Ptr). x = 4; // same as p. x = 4 Why are ( ) required?

Example struct Book { char title[50]; char author[30]; int isbn; }; int main() {

Example struct Book { char title[50]; char author[30]; int isbn; }; int main() { struct Book book 1; strcpy(book 1. title, "Pride and Prejudice"); strcpy(book 1. author, "Jane Austen"); void print. Book(struct Book *book){ book 1. isbn = 9176372065; printf("Title: %sn", book title); printf("Author: %sn", book author); // print book 1 info printf("ISBN: %dn", book isbn); print. Book(&book 1); } }

Passing Structs • Structs are passed by value – if you want the function

Passing Structs • Structs are passed by value – if you want the function to modify a struct, pass a pointer to the struct void mod. Struct(struct Book *b) { b isbn = 1234; } int main() { struct Book my. Book = {"Charlotte's Web", "E. B. White"}; mod. Struct(&my. Book); // changes isbn of my. Book }