Understanding Memory and Pointers

memory pointers n.w
1 / 32
Embed
Share

Dive into the world of memory and pointers in programming, exploring their significance in data manipulation, file I/O, and data structures. Learn about pointer arithmetic, array iteration, and how pointers can revolutionize your code efficiency.

  • Memory Management
  • Pointers Concept
  • Programming Basics
  • Data Structures
  • Pointer Arithmetic

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Memory & Pointers

  2. 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

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

  4. More on Pointers int number = 23; int *p1, *p2; number 23 p1 = &number; p2 = &number; printf ("*p1 = %d *p2 = %d ", (*p1), (*p2)); p1 p2 What s the Output ?

  5. 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

  6. 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 != '\0'; p++, i++) printf("The character at position %d is %c\n ", i, *p );

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

  8. 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 = %d\n", sum);

  9. 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 countSpaces(const char *s) { char *p; int count; count = 0; for (p = s; *p != '\0'; p++){ if (*p == ' ') count++; } return count; } int countSpaces(const char s[]){ int count, i; count = 0; for (i = 0; s[i] != '\0'; i++){ if (s[i] == ' ') 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 , countSpaces(str));

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

  11. 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 = %d\n", n); // 7 } void callerOfFoo() { int p = 30; foo(p); // the value of p copied into foo's param n printf("p = %d\n", 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

  12. 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 callerOfFoo() { int p = 30; foo(&p); // copy address of p into n printf("p = %d\n", p); // 7 } n int foo(int *n) { *n = 7; printf("*n = %d\n", *n); // 7 } p 30 7 Output when callerOfFoo() is invoked: *n = 7 p = 7

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

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

  15. 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

  16. 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 isEmpty https://en.wikipedia.org/wiki/Stack_(abstract_data_type)

  17. 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

  18. 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

  19. 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

  20. Arrays, Strings and Pointers

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

  22. 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 1st array element void arrayFn(int a[]) { int main() { int arr[] = {3, 1, 9, 0, 2}; printf("sizeof arr: %zu\n", sizeof(arr)); arrayFn(arr); } // sizeof returns bytes for int pointer printf("sizeof a: %zu\n", sizeof(a)); } Output: sizeof arr: 20 sizeof a: 8 Could change the first line of function to: void arrayFn(int *a) { ...

  23. 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(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 s = t; // compiler error Pointer vs. Array: string modification 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 sizeof: different where they can point: different!

  24. 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.

  25. 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

  26. 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 *findMiddle(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);

  27. 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(...);

  28. 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 maxMin(int *a, int len, int *minPtr, int *maxPtr) {...} int main() { int arr[] = {1, 6, 2, 4, -7, 9}; int small, large; maxMin(arr, sizeof(arr)/sizeof(arr[0]), &small, &large); printf("Min = %d\n", small); printf("Max = %d\n", large); }

  29. structs & pointers

  30. 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 *pPtr = &p; pPtr x = 3; // changes p.x int y = pPtr y; // same as y = p.y (*pPtr).x = 4; // same as p.x = 4 Why are ( ) required?

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

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

Related


More Related Content