Programming Pointers. Variables in Memory 10001003100410051012 x i c The compiler determines where variables are placed in memory This placement cannot.

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
Advertisements

Programming and Data Structure
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Kernighan/Ritchie: Kelley/Pohl:
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Pointers Discussion 5 Section Housekeeping HW 1 Issues Array Issues Exam 1 Questions? Submitting on Time!
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.
Pointers Pointer - A pointer is a derived data type; that is it is a data type built from one of the standard types. Its value is any of the addresses.
Pointers A pointer is a variable that contains memory address as its value. A variable directly contains a specific value. A pointer contains an address.
Starting out with C++1 Chapter 9 – Pointers Getting the address of a Variable Why do we have pointers? Indirection – difference between –Will you go out.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
1 Pointers ( מצביעים ). 2 Variables in memory Primitives Arrays.
1 More on Pointers. 2 Reminder 3 Pointers Pointer is a variable that contains the address of a variable Here P is said to point to the variable C C 7.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Even More C Programming Pointers. Names and Addresses every variable has a location in memory. This memory location is uniquely determined by a memory.
Overview Pointer Variables Pass by Value Pass by Reference (or by Pointer) Arrays.
1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic.
1 Agenda Variables (Review) Example Input / Output Arithmetic Operations Casting Char as a Number (if time allow)
Computer Skills2 for Scientific Colleges 1 Pointers in C++ Topics to cover: Overview of Pointers Pointer Declaration Pointer Assignment Pointer Arithmetic.
Pointers CSE 2451 Rong Shi.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Chapter 17 Pointers and Arrays. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Pointers and Arrays.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Pointers.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Lecture 6 C++ Programming Arne Kutzner Hanyang University / Seoul Korea.
Review 1 List Data Structure List operations List Implementation Array Linked List.
C Programming - Structures. Structures containing arrays A structure member that is an array does not ‘behave’ like an ordinary array When copying a structure.
Pointers *, &, array similarities, functions, sizeof.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
+ Pointers. + Content Address of operator (&) Pointers Pointers and array.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
Pointers PART - 2. Pointers Pointers are variables that contain memory addresses as their values. A variable name directly references a value. A pointer.
142 L -1 Pointers Chapter 6 C uses a call BY VALUE for functions for example: void add_one(int x, int y) { x=x+1; y=y+1; } int main(void) { int a,b; a=4;
17-Feb-02 Sudeshna Sarkar, CSE, IT Kharagpur1 Arrays and Pointers Lecture 17 18/2/2002.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
Chapter 7 Pointers Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
Pointers. What Is Pointer l every variable has memory address char c=’y’; int i=2; address of variable i is 0022 l address can used to refer to this variable.
Pointers. Introduction to pointers Pointer variables contain memory addresses as their values. Usually, a variable directly contains a specific value.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
CSCI 125 & 161 / ENGR 144 Lecture 16 Martin van Bommel.
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
CSC 215 Pointers and Arrays. Pointers C provides two unary operators, & and *, for manipulating data using pointers The operator &, when applied to a.
Computer Skills2 for Scientific Colleges
CSE 220 – C Programming Pointers.
Pointers and Pointer-Based Strings
INC 161 , CPE 100 Computer Programming
Lecture 6 C++ Programming
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
Computer Skills2 for Scientific Colleges
Outline Defining and using Pointers Operations on pointers
Pointers Lecture 2 Tue, Jan 24, 2006.
Chapter 16 Pointers and Arrays
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
C++ Pointers and Strings
Pointers and Pointer-Based Strings
Exercise Arrays.
CS1100 Computational Engineering
C++ Pointers and Strings
Pointers.
Presentation transcript:

Programming Pointers

Variables in Memory x i c The compiler determines where variables are placed in memory This placement cannot be changed by the programmer int n; char c; double x;

Address of Operator The operator & gives the address of a variable in memory  &i is 1000  &c is 1004  &x is i c x i c

Address of Operator Can only be applied to variables in memory Cannot be applied to expressions and constants  &3  &(x + 1)  &(a == b)

Address Variables (Take 1) An address is just a number let’s use an integer to hold it int address_n = &n, address_c = &c, address_x = &x; Problem?

Value Given Address The * operator access the content of a variable given its address *address_n gives the value of the variable n How can we tell how many bytes we need to read given an address? We need both the variable’s address and its size

Address Variables (Take 2) Pointers are variables that hold the address of other variables.  starting address  type (size) i c i c ip cp

A pointer is declared by adding a * before the variable name. double *dp; int *ip, n; char* cp1, *cp2; type* variable_name; Declaring a Pointer Variable pointer to double pointer to int “regular” int pointer to charanother pointer to char

Referencing The operator & gives the address of a variable ptr = &c; Assigns the address of c to the pointer ptr We say that ptr points to c

Dereferencing The operator * is the dereferencing operator Access the variable the pointer points to int n = 1, m = 2; int* ip; ip = &n; m = *ip; *ip = 0; ip is a pointer to int ip now points to x ip now points to n m is now 1 n is now 0

Is This OK? int ival = 1024, ival2 = 2048; int* pi1 = &ival, *pi2 = &ival2; ival = pi2; int int * warning C4047: '=' : 'int' differs in levels of indirection from 'int *'

Is This OK? int ival = 1024, ival2 = 2048; int* pi1 = &ival, *pi2 = &ival2; pi2 = *pi1; int * int warning C4047: '=' : 'int *' differs in levels of indirection from 'int'

Is This OK? int ival = 1024, ival2 = 2048; int* pi1 = &ival, *pi2 = &ival2; ival = *pi1; int ✓

Is This OK? int ival = 1024, ival2 = 2048; int* pi1 = &ival, *pi2 = &ival2; pi1 = ival; int * int warning C4047: '=' : 'int *' differs in levels of indirection from 'int'

NULL Special “address” indicating “nowhere” int* ip = NULL; ip does not point to any variable We can test if (ip != NULL) { *ip = …; }

Function Arguments - Reminder Changes to the local variable do not modify the value in the caller Call “by value” void increment_counter(int counter) { counter++; } int main(void) { int count;... increment_counter(count); }

We can access the variable pointed to by the local variable Call “by reference” Pointers as Function Arguments void increment_counter(int* counter) { (*counter)++; } int main(void) { int count;... increment_counter(&count); }

main incerement_counter(&count) CallerCallee main incerement_counter(count) count by value increment_counter(int counter) by reference increment_counter(int* counter) copy of count counter Pointers as Function Arguments

scanf Revisited We can now understand the & in scanf("%d", &a); The argument list in scanf is simply passed by address, so scanf can change its content

Exercise Implement the function: void split(double d, int* i_part, double* f_part); The function accepts a double parameter and assigns its integer and fraction parts to the two variable pointed to by i_part and f_part respectively. Write a program that accepts a number from the user and prints out its integer and fraction parts.

Solution void split(double d, int* i_part, double* f_part) { *i_part = (int)d; *f_part = d – (*i_part); } int main(void) { double num, fraction; int integer; printf("Please enter a real number: "); scanf("%lf", &num); split(num, &integer, &fraction); printf("The integer part is %d\n", integer); printf("The remaining fraction is %g\n", fraction); return 0; }

Example - Swap void swap(int* x, int* y) { int temp = *x; *x = *y; *y = temp; } Call swap: swap(&x, &y);

Const Pointers A pointer can be declared constant const int* cip; The pointer can be changed, but the object it points to can not. cip = &i; ✓ cip = &j; ✓ *cip = 5; ✗

Pointers as Return Values A function may return the address of a variable The variable must not be a local variable char* strchr(const char* str, char c) { while (*str != '\0') { if (*str == c) return str; ++str; } return NULL; }

Address, Pointers and Arrays int a[10]; Defines a block of 10 consecutive objects named a[0],a[1],…,a[9]. The name of the array is a synonym for the location of the first element.  a is &a[0] The name of the array is not a variable, hence its value cannot be modified. a[0] a[1]a[9] a:

Address, Pointers and Arrays a[0] a[1]a[9] a: int a[10]; int *pa; pa: int a[10]; int* pa; pa = &a[0];

Array Names are Not Pointers Pointers are variables (can be modified)  legal: pa = a pa++ Array name is not a variable (cannot be modified)  illegal: a = pa a++

Pointers Vs. Arrays - Example int arr[3] = {1, 2, 3}; int* ptr; const int* cptr; arr = ptr; ptr = arr; *ptr = 3; cptr = arr; *cptr = 5; ptr = cptr; *arr = 6;

Pointer Arithmetic If pa points to an element in the array, then pa+1 points to the next element pa+i points I elements after pa a[0] a[1]a[9] a: pa: pa+1: pa+2:

Pointer Arithmetic if pa points to a[0] *(pa + 1) is the content of a[1] *(pa + i) is equivalent to a[i]

More Pointer Arithmetic Pointers can be incremented and decremented  p++ advance p one place in the array  p += I advances p i places in the array Example: if str points to the first character of a string then str + strlen(str) -1 points to the last character

Pointers and Increment Operators Walk down an array Pointer notation  ++(*p) - increment thing pointed to  (*p)++ - increment thing pointed to  *(p++) - fetch value, then increment pointer  *(++p) - increment pointer, then fetch value int ar[ARLEN], *ip; ip = ar; while(ip < &ar[ARLEN]) *(ip++) = 0;

Reverse int main(void) { char str[STR_SIZE + 1]; char* ptr = NULL; printf("Enter a string:\n"); getline(str, STR_SIZE); for (ptr = str + strlen(str) - 1; ptr >= str; --ptr) { putchar(*ptr); } putchar('\n'); return 0; } \0 str: ptr:

my_strcpy void my_strcpy(char* dest, const char* src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } ‘y’‘e’‘s’‘\0’ src dest...

my_strcpy void my_strcpy(char* dest, const char* src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } ‘y’‘e’‘s’‘\0’ src ‘y’ dest...

my_strcpy void my_strcpy(char* dest, const char* src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } ‘y’‘e’‘s’‘\0’ src ‘y’ dest...

my_strcpy void my_strcpy(char* dest, const char* src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } ‘y’‘e’‘s’‘\0’ src ‘y’ dest...

my_strcpy void my_strcpy(char* dest, const char* src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } ‘y’‘e’‘s’‘\0’ src ‘y’ dest...

my_strcpy void my_strcpy(char* dest, const char* src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } ‘y’‘e’‘s’‘\0’ src ‘y’‘e’ dest...

my_strcpy void my_strcpy(char* dest, const char* src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } ‘y’‘e’‘s’‘\0’ src ‘y’‘e’ dest...

my_strcpy void my_strcpy(char* dest, const char* src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } ‘y’‘e’‘s’‘\0’ src ‘y’‘e’ dest...

my_strcpy void my_strcpy(char* dest, const char* src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } ‘y’‘e’‘s’‘\0’ src ‘y’‘e’ dest...

my_strcpy void my_strcpy(char* dest, const char* src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } ‘y’‘e’‘s’‘\0’ src ‘y’‘e’‘s’ dest...

my_strcpy void my_strcpy(char* dest, const char* src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } ‘y’‘e’‘s’‘\0’ src ‘y’‘e’‘s’ dest...

my_strcpy void my_strcpy(char* dest, const char* src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } ‘y’‘e’‘s’‘\0’ src ‘y’‘e’‘s’ dest...

my_strcpy void my_strcpy(char* dest, const char* src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } ‘y’‘e’‘s’‘\0’ src ‘y’‘e’‘s’ dest...

my_strcpy void my_strcpy(char* dest, const char* src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } ‘y’‘e’‘s’‘\0’ src ‘y’‘e’‘s’‘\0’ dest...

Using my_strcpy int main(void) { char str[STR_LEN + 1], temp[SR_LEN + 1];... my_strcpy(temp, str);... }

Common Error Return of a local array char* foo(const char* str) { char temp[BIG_ENOUGH]; strcpy(temp, str); /* manipulate temp */... return temp; }

Exercise Write a function with the prototype: void replace_char(char* str, char c1, char c2); It replaces each appearance of c1 by c2 in the string str. Do not use the [] operator! Demonstrate your function with a program that uses it

Solution void replace_char(char* str, char c1, char c2) { if (str == NULL) return; while (*str != '\0') { if (*str == c1) *str = c2; ++str; }