Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Slides:



Advertisements
Similar presentations
Computer Programming Lecture 14 C/C++ Pointers
Advertisements

Introduction to Programming Lecture 15. In Today’s Lecture Pointers and Arrays Manipulations Pointers and Arrays Manipulations Pointers Expression Pointers.
Programming and Data Structure
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Kernighan/Ritchie: Kelley/Pohl:
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
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.
Dale/Weems/Headington
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
1 9/10/07CS150 Introduction to Computer Science 1 Data Types Section 2.7 – 2.12 CS 150 Introduction to Computer Science I.
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
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.
Starting Out with C++, 3 rd Edition 1 Chapter 9 – Pointers.
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.
CS150 Introduction to Computer Science 1
What is the out put #include using namespace std; void main() { int i; for(i=1;i
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Lecture 2 Arrays, Pointers, and Structures. Objective In this chapter, we will discuss several concepts: Arrays (first-class arrays, using vector) Strings.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 2 Introduction to C++
POINTERS. 1.a) POINTER EXPRESSIONS Pointer variables can be used in expression If p1 and p2 are properly declared and initialized pointers then following.
Pointer Data Type and Pointer Variables. Objectives: Pointer Data Type and Pointer Variables Pointer Declaration Pointer Operators Initializing Pointer.
C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas.
1 Pointers and Arrays. 2 When an array is declared,  The compiler allocates sufficient amount of storage to contain all the elements of the array in.
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
Dynamic memory allocation and Pointers Lecture 4.
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.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
CS102 Introduction to Computer Programming Chapter 9 Pointers.
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 A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed.
Pointer in C++ Dr. Ahmed Telba. Topics Covered Introduction to Pointers Pointers and arrays Character Pointers, Arrays and Strings Examples.
Pointers *, &, array similarities, functions, sizeof.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Computer And Programming Array and Pointer. Array provides a means to allocating and accessing memory. Pointers, on the other hand, provides a way to.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
DCT1063 Programming 2 CHAPTER 1 POINTERS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Variables and memory addresses
Pointers PART - 2. Pointers Pointers are variables that contain memory addresses as their values. A variable name directly references a value. A pointer.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 7 – Pointers.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
POINTERS IN C Pointer Basics, Pointer Arithmetic, Pointer to arrays and Pointer in functions.
CS162 - Topic #12 Lecture: –Arrays with Structured Elements defining and using arrays of arrays remember pointer arithmetic Programming Project –Any questions?
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
A Sample Program #include using namespace std; int main(void) { cout
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
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.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Prepared by Andrew Jung. Accessing Pointer Data Pointer can be used to access the contents of an array Look at the following syntax: /* Declaration and.
Basic Concepts:- Invalid use of Address Operator &75 &(‘a’) &(a+b)
Pointers A variable that holds an address value is called a pointer variable, or simply a pointer.  What is the data type of pointer variables? It’s not.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
Pointers What is the data type of pointer variables?
Student Book An Introduction
Programming Languages and Paradigms
Andy Wang Object Oriented Programming in C++ COP 3330
Programming Funamental slides
Pointers.
Presentation transcript:

Pointers in C++

Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples

Introduction to Pointers  When we declare a variable some memory is allocated for it. The memory location can be referenced through the identifier “i”. Thus, we have two properties for any variable : its address and its data value. The address of the variable can be accessed through the referencing operator “&”. “&i” gives the memory location where the data value for “i” is stored.  A pointer variable is one that stores an address. We can declare pointers as follows int* p;.This means that p stores the address of a variable of type int.

Introduction to Pointers  Q: Why is it important to declare the type of the variable that a pointer points to? Aren’t all addresses of the same length?  A: It’s true that all addresses are of the same length, however when we perform an operation of the type “p++” where “p” is a pointer variable, for this operation to make sense the compiler needs to know the data type of the variable “p” points to. If “p” is a character pointer then “p++” will increment “p” by one byte (typically), if “p” were an integer pointer its value on “p++” would be incremented by 2 bytes (typically).

Introduction to Pointers  Summary of what was learnt so far: Pointer is a data type that stores addresses, it is declared as follows:int* a; char* p; etc. The value stored in a pointer p can be accessed through the dereferencing operator “*”. The address of a memory location of a variable can be accessed through the reference operator “&”. Pointer arithmetic: only addition and subtraction are allowed. Type *ptr=&var int x=5; int *ptr=&x;

Pointers and Arrays  The concept of array is very similar to the concept of pointer. The identifier of an array actually a pointer that holds the address of the first element of the array.  Therefore if you have two declarations as follows: “int a[10];” “int* p;” then the assignment “p = a;” is perfectly valid Also “*(a+4)” and “a[4]” are equivalent as are “*(p+4)” and “p[4]”. The only difference between the two is that we can change the value of “p” to any integer variable address whereas “a” will always point to the integer array of length 10 defined.

Character Pointers, Arrays and Strings  What is a String? A string is a character array that is ‘\0’ terminated. E.g. “Hello”  What is a Character array? It is an array of characters, not necessarily ‘\0’ terminated E.g. char test[4] = {‘a’, ‘b’, ‘c’, ‘d’};  What is a character pointer? It is a pointer to the address of a character variable. E.g. char* a;

Print location of pointer  #include  main()  {int x=5;  int *ptr=&x;  cout<<"location Ptr="<<ptr;  cout<<"\nlocation var="<<&x;  cout<<"\nvalue Ptr="<<*ptr;  cout<<"\n value var="<<x;  system("pause");  }

Change value of pointer #include main() {int g=5; int *ptr=&g; *ptr=32; cout<<"\nx="<<g; system("pause"); }

 #include  main()  {int g=15,item;  int *ptr=new int [1];  *ptr=32;  item=*ptr;  *ptr=g;  g=item;  cout<<"\ng="<<g<<"\n*ptr="<<*ptr;  system("pause");  }

Array in pointer  #include  main()  { int i, first_array[5]={34,26,43,23,54};  int *ptr=& first_array[0];  for(i=0;i<5;i++){  *(ptr+i)=*(ptr+i)+14;  cout<<"\n first_array["<<i<<"]="<<*(ptr+i);}  system("pause");  }

Sum of array using pointer  /  #include  main()  { int sum=0, first_array[3]={ 43,23,54};  int *ptr=& first_array[0];  sum+=*ptr++;  cout<<"\n sum="<<sum;  system("pause");  }

Multi dimetnenal array  Int first_array[2][2]={{34,26},{43,23} };  int *ptr=& first_array[0][0]

Multiply by *4  #include  main()  { int i, j,first_array[2][2]={{34,26},{43,23} };  int *ptr=& first_array[0][0];  for(i=0;i<2*2;i++)  *(ptr+i)=*(ptr+i)*4;  for(i=0;i<2 ;i++){  for(j=0;j<2 ;j++)  cout<< first_array[i][j];  cout<<"\n";}  system("pause");}

Adding using pointer  #include  main()  { int sum=0, first_array[2][2]={{34,26},{43,23} };  int *ptr=& first_array[0][0];  sum+=*ptr++;  cout<<"\n sum="<<sum;}

Function using pointer(change small to capital letters )  #include  inline toBigLeter (char *ptr)  {*ptr=int(*ptr)-32;}  main()  { char inputchar;  cin>> inputchar;  toBigLeter (& inputchar );  cout<<"Big to it is="<< inputchar;}

Add anf find average of matrix  #include  main( )  {int sizearray,j,sum,avg;  sum=0;  cout<<"who size the arrray\n" ;  cin>> sizearray ;  int *Array=new int [ sizearray ];  cout<<"enter the array\n" ;  for ( j=0;j<sizearray; j++)  cin>> Array[j] ;  for (j=0;j<sizearray; j++)  sum=sum+Array[j];  avg=sum/sizearray;  cout<<"sum="<<sum<<"\navg= "<<avg;  system("pause");}

Inter matrix and find diameter  #include  void main ( )  { int i,j,k,sum,rowN,colN;  sum=0;  cin>>rowN>>colN ;  int **Array=new int *[ rowN ];  for (k=0 ; k< rowN ; k++)  Array[k]=new int[ colN ];  for (i=0 ; i< rowN ; i++)  for (j=0; j< colN ; j++)  cin>>Array[i][j] ;  for (i=0 ; i< rowN ; i++)  for (j=0; j< colN ; j++)  if (i==j)  sum=sum+ Array[i][j];  cout<<"sum="<<sum ;}

Character Pointers, Arrays and Strings  How do we initialize a Character pointer? Initialize it to NULL. char* a = NULL; Let it point to a character array.  char* a; char b[100]; a = b; Initialize to a character string.  char* a = “Hello”; a pointer to the memory location where ‘H’ is stored. Here “a” can be viewed as a character array of size 6, the only difference being that a can be reassigned another memory location.

Examples  char* a = “Hello”; a -> gives address of ‘H’ *a -> gives ‘H’ a[0] -> gives ‘H’ a++ -> gives address of ‘e’ *a++ -> gives ‘e’ a = &b; where b is another char variable is perfectly LEGAL. However “char a[100];” “a =&b;” where b is another char variable is ILLEGAL.

Pointer in C++  Pointer in C++

Pointer in C++  c = a; // c == 1176  c = *a; // c ==25  b == 25  &b == 1776  a == 1776  *a == 25  *a == b

 int * number;  char * character;  float * greatnumber; Pointer can be : // my first pointer #include using namespace std; int main () { int a = 5, b = 15; int *ptr; ptr= &a; *ptr = 10; ptr = &b; *ptr = 20; cout<<"a="<<a<<", b="<<b; return 0; }

more pointers  #include  using namespace std;  int main ()  {  int a = 5, b = 15;  int *p1, *p2;  p1 = &a;  p2 = &b;  *p1 = 10;  *p2 = *p1;  p1 = p2;  *p1 = 20;  cout << "a=" << a << ", b=" << b;  return 0;  }

// more pointers  #include  using namespace std;  int main ()  {  int numbers[5];  int * p;  p = numbers; *p = 10;  p++; *p = 20;  p = &numbers[2]; *p = 30;  p = numbers + 3; *p = 40;  p = numbers; *(p+4) = 50;  for (int n=0; n<5; n++)  cout << numbers[n] << ", ";  return 0;  }

Matrix of pointer  char* cars[3];  char[0]="Mercedes";  char[1]="Nissan";  char[2]="Ferrari";

more pointers  char a;  char * b;  char ** c;  a = 'z';  b = &a;  c = &b;

// integer increaser sizeof #include using namespace std; void increase (void* data, int type) { switch (type) { case sizeof(char) : (*((char*)data))++; break; case sizeof(short): (*((short*)data))++; break; case sizeof(long) : (*((long*)data))++; break; } int main () { char a = 5; short b = 9; long c = 12; increase (&a, f(a)); increase (&b,sizeof(b)); increase (&c,sizeof(c)); cout << (int) a << ", " << b << ", " << c; return 0; }

// pointer to functions #include using namespace std; int addition(int a, int b) { return (a+b); } int subtraction(int a, int b) { return (a-b); } int (*minus)(int,int) = subtraction;//pointer to function int operation(int x, int y, int (*p)(int,int)) { int g; g = (*p)(x,y); return (g); } int main () { int m,n; m = operation(7, 5, addition); n = operation(20, m, minus); cout <<n; return 0; }

Example about structures // example about structures #include using namespace std; #include struct students{ char name[50]; char city[50]; int tel; }st1,st2; int main() { //filling information cout<<"enter student1 name, city and tel_no: "; cin>>st1.name; cin>>st1.city; cin>>st1.tel; cout<<"enter student2 name, city and tel_no: "; cin>>st2.name; cin>>st2.city; cin>>st2.tel; //printing information cout<<"\nname"<<"\tcity\t"<<"tel_no"; cout<<"\n \n"; cout<<st1.name<<"\t"<<st1.city<<"\t"<<st1.tel<<endl; cout<<st2.name<<"\t"<<st2.city<<"\t"<<st2.tel<<endl; return 0; }

Print array and summing  #include  using namespace std;  int main()  {  int A[]={5,6,1,9,12,4,7};  int sum=0;  for(int i=0;i<7;i++)  {  cout<<A[i]<<" ";  sum+=A[i]; //sum =sum+A[i];  }  cout<<"\nsum= "<<sum<<endl;  return 0;  }

Fibonacci Sequence #include using namespace std; // int f[1000]; int fib(int n) { f[0] = 0; f[1] = 1; for(int i=2; i<=n;i++) f[i] = f[i-1]+f[i-2]; return f[n]; } int main() { int n ; cout<< "Enter n: "; cin>> n; cout<< "\nfib(" << n << ") = " << fib(n) << endl; }