CSCI 171 Presentation 11 Pointers. Pointer Basics.

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Programming and Data Structure
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
Managing Memory DCT 1063 PROGRAMMING 2 Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Engineering Problem Solving with C Fundamental Concepts Chapter 6 Pointers.
Kernighan/Ritchie: Kelley/Pohl:
Memory Allocation. Memory A memory or store is required in a computer to store programs (or information or data). Data used by the variables in a program.
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
1 Day 03 Introduction to C. 2 Memory layout and addresses r s int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘r’, d = ‘s’;
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
Chapter 10.
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
Pointers Applications
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 Programming with Pointers Turgay Korkmaz Office: SB Phone: (210) Fax: (210) web:
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Stack and Heap Memory Stack resident variables include:
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to.
1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Pointers.
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Pointers *, &, array similarities, functions, sizeof.
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Dynamic Memory Allocation. 2 In everything we have done so far, our variables have been declared at compile time. In these slides, we will see how to.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
CSE 220 – C Programming malloc, calloc, realloc.
Stack and Heap Memory Stack resident variables include:
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Chapter 8 Arrays, Strings and Pointers
POINTERS.
Lecture 6 C++ Programming
Object Oriented Programming COP3330 / CGS5409
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
Memory Allocation CS 217.
Programming with Pointers
Outline Defining and using Pointers Operations on pointers
Dynamic Memory – A Review
Presentation transcript:

CSCI 171 Presentation 11 Pointers

Pointer Basics

Why use pointers? Some routines can be more efficiently written with pointers Some routines need pointers

Memory Usage Programmer declares a variable int x; Compiler sets aside memory 4 bytes for an integer Memory has a unique address Address and variable name are associated Address is hidden from the programmer

Memory Address Address is an integer Can be printed out with %p –result represents a segment and an offset what segment of memory the location is in what offset (how far from the start of the segment) the location is –Most compilers show the two separated by a colon –Code Warrior does not

Pointers Address can be stored in another variable –pointer Pointer - variable that contains the address of another variable

Using Pointers Pointers must be declared before use Names must be unique Declaration: typename * ptrname; int * x; * - Indirection operator –Informs the compiler that the variable is a pointer

Initializing Pointers Pointers must be initialized –Always initialize pointers to NULL –int * ptr = NULL; –Symbolic constant for 0 Impossible to know what uninitialized pointers are pointing to –could be anywhere in memory

Address of Operator & - address of operator int x = 3; &x is interpreted as ‘the address of x’ Sample code: int x = 3; int * y = NULL; y = &x;

Using Pointers Once a pointer has been declared and initialized it can be used When indirection operator (*) precedes a pointer, it refers to the contents of the variable to which it points

Using Pointers - Example int x = 3; int *y = NULL; y = &x; printf(“%d”, *y); The preceding code results in 3 printed to the screen

Accessing Information Definitions Direct Access - accessing contents of a variable using the variable name Indirect Access - accessing the contents of a variable by using a pointer to the variable

Accessing Information Assume ptr is a pointer variable that points to the variable var –*ptr and var each refer to the contents of var –ptr and &var each refer to the address of var

Using Pointers - Example int x = 3, *y = NULL; y = &x; printf(“%d”, x); printf(“%d”, *y); printf(“%p”, &x); printf(“%p”, y); } Equivalent Statements } Equivalent statements

Arrays and Pointers The name of an array is a pointer to the array –points to the first byte of the first element –remains fixed throughout program execution Example: if int x[10] is an array declaration, then x and &x[0] are equivalent both represent the addresses of the first array element

Arrays and Pointers Consider the following code: int array[3] = {1, 2, 3}, *ptr = NULL, z=2; ptr = array; –array points to the first element in the array cannot be changed array = &z; causes a compiler error –ptr points to the first element in the array can be changed ptr = &z; does not cause a compiler error

Pointer Arithmetic Pointers are often manipulated arithmetically –incremention –decrementation The compiler ‘knows’ the size of a data type, and will increment the address accordingly –adding 1 to an integer pointer increments the address by 4 integers take up 4 bytes of space

Using pointer arithmetic - Ex. 1 Print out the contents of a 10 element integer array using pointer arithmetic int main( void ) { int x[10] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}, *y = NULL, count; y = x; for (count = 0; count < 10; count++) printf("%d ", *y++); }

Using pointer arithmetic - Ex. 2 #include int main( void ) { int x[5] = {2, 4, 6, 8, 10}, *y = NULL, count = 0; char a[5] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’}, *b = NULL; y = x; b = a; for (count = 0; count < 5; count++) { printf("\n%d ", *y++); //incrementing y increments the pointer 4 bytes printf("\n%c ", *b++);//incrementing b increments the pointer 1 byte }

Other pointer arithmetic Incrementation, decrementation are valid +, - must be an integer (compiler error if not) Other arithmetic is not valid *, /, %, etc.

Valid Pointer Operations

Pointers and Functions Arrays cannot be passed into functions, but pointers can –In our programs when we pass in an array, we have actually passed in a pointer Prototype of a function that accepts an array int func1(int []); int func1(int x[]); int func1(int *x); } Almost equivalent, only difference is the first does not specify variable name

Sample Program #include void changeInt(int *); int main( void ) { int *ptr = NULL, var = 0; ptr = &var; changeInt(ptr); printf("The variable ptr is pointing to: %d", *ptr); return 0; } void changeInt(int * argPtr) { *argPtr = 11; }

Characters, strings, and an introduction to dynamic memory allocation

Strings arrays of characters char string[10]; string: array of characters ending with the null character –null character: ‘\0’ To store ‘Computer’ in a string, need an array of 9 characters (8 for the letters, one for the null character)

String Initialization Strings can be initialized many ways: char string1[10] = “Hello”; char string2[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’}; char string3[] = “Hi”; What is the output of the following? printf(“%d %d %d”, sizeof(string1), sizeof(string2), sizeof(string3); Answer:

String / Pointer Relationship Recall: Array name is a pointer to the first element in the array Character array is a pointer to the first element in an array –i.e. the beginning of the string ‘\0’ indicates the end of the string Array size is incidental Array name, and ‘\0’ give us all the information we need

String / Pointer Relationship

Allocating Strings Strings can be allocated without actually declaring an array –Only the pointer to the first character and the ‘\0’ is needed Example: char * msg = “Hello”;is equivalent to: char msg[] = “Hello”;

Dynamic Allocation of Strings Dynamic memory allocation –allocating memory ‘on the fly’ –memory allocated at program execution time –using the malloc( ) function is one way to do this Always include Example: char *ptr = NULL; ptr = malloc(5);

malloc( ) function returns an address –pointer to type void –can store any of C’s data types accepts an integer parameter allows for more efficient memory usage

Possible errors with malloc( ) If there is not enough memory for malloc( ) to complete the request, malloc( ) returns null Return value should ALWAYS be checked

Sample code using malloc( ) #include int main( void ) { char *ptr = NULL; ptr = malloc(10); if (ptr = = NULL) printf("Memory not allocated"); else printf("Successful allocation of memory"); return 0; }

Sample code using malloc( ) #include int main( void ) { char *ptr = NULL; if ((ptr = malloc(10)) = = NULL) printf("Memory not allocated"); else printf("Successful allocation of memory"); return 0; }

Sample code using malloc( ) Structured example #include int main( void ) { char *ptr = NULL; if ((ptr = (char *)malloc(10 * sizeof(char))) = = NULL) { printf("Memory not allocated"); exit(1); } //Code continues from this point return 0; }

Displaying Strings - puts( ) puts( ) accepts a pointer to a string –string literal evaluates as a pointer to a string prints the string to the screen automatically inserts new line character at end of string Example: char * name = “CSCI 131”; puts(name); puts(“this is a string literal”);

Displaying Strings - printf( ) %s is the string conversion specifier Example: char * ptr = "Hello"; printf("%s", ptr); printf("%s\n%s", ptr, "there");

Accepting strings from keyboard Two options –gets( ) –scanf( )

Accepting strings - gets( ) Reads all characters up to first new line Discards new line, adds ‘\0’ to end Returns value as a string (ptr to type char)

Accepting strings - gets( ) Example: #include int main( void ) { char name[15]; printf(“Enter your name\n”); gets(name); }

Accepting strings - scanf( ) Reads all characters up to first occurrence of whitespace Adds ‘\0’ to end Returns value as a string (ptr to type char)

Accepting strings - scanf( ) Sample code: puts(“Enter your name”) scanf(“%s”, x);

Can scan a specific number of characters Sample code (scans first 3 characters): puts(“Enter your name”) scanf(“%3s”, x);

gets( ) verses scanf( ) gets( ) is good when entering text scanf( ) is useful when entering text and numeric values, or just numeric values

Memory management and more advanced dynamic memory allocation

Type Casting Consider the following code: #include int main( void ) { int i = 3, j = 2; float z = 0.0; z = i / j; printf("%f", z); } Output:

Type Casting Solving the problem on the previous slide: #include int main( void ) { int i = 3, j = 2; float z = 0.0; z = (float)i / (float)j; //Typecast the i and j to floats printf("%f", z); } Output:

Casting Pointers #include int main( void ) { void * x = NULL; int p = 3; (int *)x = &p;//Type casting the void pointer to a //integer pointer printf("%d", *(int *)x);//Type casting and dereferencing return 0; }

Memory Allocation Static allocation –explicitly allocating memory in source code –allocation determined at compile time Dynamic allocation –allocating memory at run time occurs during program execution

Memory Allocation functions stdlib.h file Allocating and freeing memory –malloc( ) –calloc( ) –realloc( ) –free( )

malloc( ) function revisited returns an address –pointer to type void –can store any of C’s data types accepts an integer parameter allows for more efficient memory usage malloc( ) is not restricted to character arrays should cast the returned pointer

malloc( ) example #include int main( void ) { int *x = NULL, y = 0, i = 0; printf("Enter the number of elements for an array: "); scanf("%d", &y); if (x = (int *)malloc(y*(sizeof(int))) = = NULL) printf("Memory not allocated"); exit(1); } for (i = 0; i < y; i++) *(x+i) = 0;//Can access the elements using //pointer arithmetic for (i = 0; i < y; i++) printf("%d", x[i]);//Can access the elements using }//array notation

calloc( ) function similar to malloc accepts 2 parameters –number of objects –bytes per object clears allocated memory –initializes to binary 0 returns a type void pointer –return value should be cast

Sample code using calloc( ) #include int main( void ) { int *ptr = NULL; if ((ptr = (int *)calloc(10, (sizeof(int)))) = = NULL) { printf("Memory not allocated"); exit(1); } printf("Successful allocation of memory"); return 0; }

realloc( ) function Changes size of memory block allocated by malloc( ) or calloc( ) Accepts 2 parameters –pointer –new size (in bytes) Functionality depends on several factors

realloc( ) functionality 1. Current space can be expanded –space is allocated, original pointer is returned 2. Current space cannot be expanded –new block is allocated –existing data is copied from old to new block –old block is freed –pointer to new block is returned

realloc( ) functionality 3. pointer argument is NULL –function acts like malloc( ) 4. argument size is 0 –memory pointer argument points to is freed –function returns NULL 5. memory cannot be allocated –function returns NULL –original block unchanged

Sample code using realloc( ) #include int main( void ) { int *ptr = NULL; if ((ptr = (int *)calloc(10, sizeof(int))) == NULL) { printf("Memory not allocated"); exit(1); } else printf("Successful allocation of memory"); if ((ptr = (int *)realloc(ptr, 50*sizeof(int))) == NULL) { printf("\nMemory reallocation unsuccessful"); exit(1); } else printf("\nSuccessful reallocation of memory"); return 0; }

free( ) function When dynamically allocated memory is no longer needed, the resources should be freed –amount of memory available for allocation is finite Passing the pointer to the free( ) function will free up memory free( ) function –accepts a pointer as an argument –has no return value (i.e. void)

Sample code using free( ) #include int main( void ) { int *ptr = NULL; if ((ptr = (int *)calloc(10, sizeof(int))) == NULL) { printf("Memory not allocated"); exit(1); } else printf("Successful allocation of memory"); free(ptr); return 0; }

Memory Leaks #include int main( void ) { int *ptr = NULL; if ((ptr = (int *)calloc(10, sizeof(int))) == NULL) { printf("Memory not allocated"); exit(1); } //Code using ptr would go here if ((ptr = (int *)calloc(12, sizeof(int))) == NULL) { printf("Memory not allocated"); exit(1); } //More code using pointer would go here return 0; }

Avoiding Memory Leaks #include int main( void ) { int *ptr = NULL; if ((ptr = (int *)calloc(10, sizeof(int))) == NULL) { printf("Memory not allocated"); exit(1); } //Code using ptr would go here free(ptr); if ((ptr = (int *)calloc(12, sizeof(int))) == NULL) { printf("Memory not allocated"); exit(1); } //More code using pointer would go here return 0; }

Avoiding Memory Leaks #include int main( void ) { int *ptr = NULL; if ((ptr = (int *)calloc(10, sizeof(int))) == NULL) { printf("Memory not allocated"); exit(1); } //Code using ptr would go here if ((ptr = (int *)realloc(ptr, 48*sizeof(int))) == NULL) { printf("Memory not allocated"); exit(1); } //More code using pointer would go here return 0; }

Passing Values to Functions Passing by Value –Changes to the parameter do not affect changes to the argument Passing by Reference –Arrays, pointers –Changes to the parameter do affect changes to the argument

Passing by Value x = 5; myFunction(x) –causes a copy of x to be made, and accessible to the function Changes at addresses do not affect the contents of addresses

Passing by Reference Used with arrays and pointers myFunction(&x) –causes the address of x to be passed to the function Changes are made at the address (1000), and hence changes made in the function are reflected in the calling function

Why pass by Reference? If you need to modify the argument (i.e. if you need to modify the value of the variable in the calling program within the function) If you are using arrays

Passing by Reference Passing by reference Advantage: The function can modify the value of the argument Disadvantage: The function can modify the value of the argument Passing by reference should be avoided unless there is a specific reason for doing it

Passing by Value Ex: #include void changeVal(int); main( void ) { int x = 3; changeVal(x); printf("\nx in the main function is: %d", x); } void changeVal(int x) { x = x * 6; printf("x in the changeVal function is: %d", x); }

Passing by Reference Ex 1: #include void changeVal(int *); main( void ) { int x = 3; changeVal(&x); printf("\nx in the main function is: %d", x); } void changeVal(int * x) { *x = *x * 6; printf("x in the changeVal function is: %d", *x); }

Passing by Reference Ex 2: #include void changeVal(int []); main( void ) { int x[2] = {3, 6}; changeVal(x); printf("\nx in the main function is: %d %d", x[0], x[1]); } void changeVal(int x[]) { x[0] = x[0] * 2; x[1] = x[1] * 2; printf("x in the changeVal function is: %d %d", x[0], x[1]); }