Pointers. 2 A pointer is a variable that points to or references a memory location in which data is stored. Each memory cell in the computer has an address.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

UNIT 9: Pointers Data Variable and Pointer Variable Pass by Reference
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Chapter 10 Pointers and Dynamic Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Pointers Pointer variables.
Problem Solving & Program Design in C
Pointer Lesson 2 CS1313 Spring Pointer Lesson 2 Outline 1.Pointer Lesson 2 Outline 2.Pass by Reference Bad Example 3.Pass by Reference Good Example.
Chapter 7: Arrays In this chapter, you will learn about
Numerical Recipes The Art of Scientific Computing (with some applications in computational physics)
Malloc Recitation By sseshadr. Agenda Macros in C Pointer declarations Casting and Pointer Arithmetic Malloc.
1 Chapter Eleven Arrays. 2 A Motivating Example main( ) { int n0, n1, n2, n3, n4; scanf(“%d”, &n0); scanf(“%d”, &n1); scanf(“%d”, &n2); scanf(“%d”, &n3);
C Language.
Spring Semester 2013 Lecture 5
An introduction to pointers in c
Lectures 10 & 11.
Pointers and Arrays Chapter 12
Pointers Pointer is a variable that contains the address of a variable Here P is sahd to point to the variable C C 7 34……
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 12P. 1Winter Quarter User-Written Functions.
Data Structures Using C++ 2E
Senem KUMOVA METİN CS FALL 1 POINTERS && ARRAYS CHAPTER 6.
Call By Address Parameters (Pointers) Chapter 5. Functions that “return” more than a single value What if we need more than one value to be returned from.
Computer Programming w/ Eng. Applications
1 Chapter Thirteen Pointers. 2 Pointers A pointer is a sign used to point out the direction.
Chapter 9 Pointers and Dynamic Arrays. Overview 9.1 Pointers 9.2 Dynamic Arrays.
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.
Kernighan/Ritchie: Kelley/Pohl:
Introduction to C Programming
CSI 3125, Preliminaries, page 1 Polymorphism, Virtual function.
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.
Pointers Discussion 5 Section Housekeeping HW 1 Issues Array Issues Exam 1 Questions? Submitting on Time!
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.
Even More C Programming Pointers. Names and Addresses every variable has a location in memory. This memory location is uniquely determined by a memory.
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. 1.a) POINTER EXPRESSIONS Pointer variables can be used in expression If p1 and p2 are properly declared and initialized pointers then following.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
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.
Arithmetic Operations. Review function statement input/output comment #include data type variable identifier constant declaration.
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:
C OMPUTER P ROGRAMMING 1 Assignment. A SSIGNMENT We have used gets to input a value into variable The second way to give a variable a value is known as.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Pointers *, &, array similarities, functions, sizeof.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
C Programming Lecture 16 Pointers. Pointers b A pointer is simply a variable that, like other variables, provides a name for a location (address) in memory.
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.
Pointers PART - 2. Pointers Pointers are variables that contain memory addresses as their values. A variable name directly references a value. A pointer.
Pointer. lvalues In C++, any expression that refers to an internal memory location is called an lvalue Appear on left side of assignment statement e.g.
CCSA 221 Programming in C CHAPTER 11 POINTERS ALHANOUF ALAMR 1.
Pointers in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
 Most C programs perform calculations using the C arithmetic operators (Fig. 2.9).  Note the use of various special symbols not used in algebra.  The.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9-1 Pointer Variables Pointer variable : Often just called a pointer, it's.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
CSCI 125 & 161 / ENGR 144 Lecture 16 Martin van Bommel.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Windows Programming Lecture 03. Pointers and Arrays.
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.
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
Pointers.
Pointers and Pointer-Based Strings
INC 161 , CPE 100 Computer Programming
Overloading functions
Pointers and Pointer-Based Strings
Introduction to Pointers
Introduction to Pointers
Presentation transcript:

Pointers

2 A pointer is a variable that points to or references a memory location in which data is stored. Each memory cell in the computer has an address that can be used to access that location so a pointer variable points to a memory location we can access and change the contents of this memory location via the pointer.

3 Pointers Pointer declaration: A pointer is a variable that contains the memory location of another variable. The syntax is as shown below. Start by specifying the type of data stored in the location identified by the pointer. The asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the variable. type * variable name Example: int *ptr; float *string;

4 Pointers Address operator: Once we declare a pointer variable we must point it to something we can do this by assigning to the pointer the address of the variable you want to point as in the following example: ptr=# This places the address where num is stores into the variable ptr. If num is stored in memory address then the variable ptr has the value

5 Pointers /* A program to illustrate pointer declaration*/ #include main() { int *ptr; int sum; sum=45; ptr=∑ printf("\n Sum is %d",sum); printf("\n The sum pointer is %u", ptr); }

Cox & NgArrays and Pointers6 int i1; int i2; int *ptr1; int *ptr2; i1 = 1; i2 = 2; ptr1 = &i1; ptr2 = ptr1; *ptr1 = 3; i2 = *ptr2; i1: i2: ptr1: 0x1000 0x1004 0x1008 … ptr2: … 0x100C 0x1010 0x x Pointers

7 Pointer expressions & pointer arithmetic: Like other variables pointer variables can be used in expressions. For example if p1 and p2 are properly declared and initialized pointers, then the following statements are valid. y=*p1**p2; sum=sum+*p1; z= 5* - *p2/p1; *p2= *p2 + 10; C allows to add integers to or subtract integers from pointers as well as to subtract one pointer from the other. We can also use short hand operators with the pointers p1+=; sum+=*p2; etc., we can also compare pointers by using relational operators the expressions such as p1 >p2, p1==p2 and p1!=p2 are allowed.

8 Pointers /*Program to illustrate the pointer expression and pointer arithmetic*/ #include main() { int *ptr1,*ptr2; int a,b,x,y,z; a=30;b=6; ptr1=&a; ptr2=&b; x=*ptr1+ *ptr2- 6; y=6*- *ptr1/ *ptr2 +30; printf("\na=%d, b=%d",a,b); printf("\nx=%d,y=%d",x,y); }

9 Pointers Pointers and function: 1. Call by reference 2. Call by value. Call by Reference: When we pass address to a function the parameters receiving the address should be pointers. The process of calling a function by using pointers to pass the address of the variable is known as call by reference. The function which is called by reference can change the values of the variable used in the call.

10 Pointers /* example of call by reference*/ #include void main() { void fncn(int *,int *); int a=20,b=30; printf("\n Value of a and b before function call =%d %d",a,b); fncn(&a,&b); printf("\n Value of a and b after function call =%d %d",a,b); } void fncn(int *p,int *q) { *p=100; *q=200; }

11 Pointers Pointer to arrays: An array is actually very much like pointer. We can declare the arrays first element as a[0] or as int *a because a[0] is an address and *a is also an address the form of declaration is equivalent. The difference is pointer is a variable and can appear on the left of the assignment operator that is lvalue. The array name is constant and cannot appear as the left side of assignment operator.

12 Pointers /* A program to display the contents of array using pointer*/ #include main() { int a[100]; int i,j,n,*ptr; printf("\nEnter the elements of the array\n"); scanf("%d",&n); printf("Enter the array elements"); for(i=0;i< n;i++) { scanf("%d",&a[i]); } printf("Array element are"); for(ptr=a;ptr<(a+n);ptr++) { printf("\nValue of stored at address %u",ptr); }

13 Pointers Multi-Dimensional Arrays int multi[ROWS][COLS]; we can access individual elements of the array multi using either: multi[row][col] or *(*(multi + row) + col) To understand more fully what is going on, let us replace *(multi + row) with X as in: *(X + col) Now, from this we see that X is like a pointer since the expression is de- referenced and we know that col is an integer. The arithmetic being used here is of a special kind called "pointer arithmetic". That means that, since we are talking about an integer array, the address pointed to by (i.e. value of) X + col + 1 must be greater than the address X + col by and amount equal to sizeof(int).

14 Pointers Since we know the memory layout for 2 dimensional arrays, we can determine that in the expression multi + row as used above, multi + row + 1 must increase by value an amount equal to that needed to "point to" the next row, which in this case would be an amount equal to COLS * sizeof(int). That says that if the expression *(*(multi + row) + col) is to be evaluated correctly at run time, the compiler must generate code which takes into consideration the value of COLS, i.e. the 2nd dimension. Because of the equivalence of the two forms of expression, this is true whether we are using the pointer expression as here or the array expression multi[row][col].

15 Pointers Thus, to evaluate either expression, a total of 5 values must be known: The address of the first element of the array, which is returned by the expression multi, i.e., the name of the array. The size of the type of the elements of the array, in this case sizeof(int). The 2nd dimension of the array The specific index value for the first dimension, row in this case. The specific index value for the second dimension, col in this case. Given all of that, consider the problem of designing a function to manipulate the element values of a previously declared array. For example, one which would set all the elements of the array multi to the value 1.

16 Pointers More on Strings Well, we have progressed quite a way in a short time! Let's back up a little and look at what was done in Chapter 3 on copying of strings but in a different light. Consider the following function: char *my_strcpy(char dest[], char source[]) { int i = 0; while (source[i] != '') { dest[i] = source[i]; i++; } dest[i] = ''; return dest; } Recall that strings are arrays of characters. Here we have chosen to use array notation instead of pointer notation to do the actual copying. The results are the same, i.e. the string gets copied using this notation just as accurately as it did before. This raises some interesting points which we will discuss. Since parameters are passed by value, in both the passing of a character pointer or the name of the array as above, what actually gets passed is the address of the first element of each array. Thus, the numerical value of the parameter passed is the same whether we use a character pointer or an array name as a parameter. This would tend to imply that somehow source[i] is the same as *(p+i).

17 Pointers Pointers to Functions Up to this point we have been discussing pointers to data objects. C also permits the declaration of pointers to functions. Pointers to functions have a variety of uses and some of them will be discussed here. Consider the following real problem. You want to write a function that is capable of sorting virtually any collection of data that can be stored in an array. This might be an array of strings, or integers, or floats, or even structures. The sorting algorithm can be the same for all. For example, it could be a simple bubble sort algorithm, or the more complex shell or quick sort algorithm. We'll use a simple bubble sort for demonstration purposes. Sedgewick [1] has described the bubble sort using C code by setting up a function which when passed a pointer to the array would sort it. If we call that function bubble(), a sort program is described by bubble_1.c, which follow

18 Pointers /* Program bubble_3.c from PTRTUT10.HTM 6/13/97 */ #include int arr[10] = { 3,6,1,2,3,8,4,1,7,2}; void bubble(int *p, int N); int compare(int *m, int *n); int main(void) { int i; putchar(' '); for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } bubble(arr,10); putchar(' '); for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } return 0; } void bubble(int *p, int N) { int i, j, t; for (i = N-1; i >= 0; i--) { for (j = 1; j <= i; j++) { if (compare(&p[j-1], &p[j])) { t = p[j-1]; p[j-1] = p[j]; p[j] = t; } int compare(int *m, int *n) { return (*m > *n); }

19 Pointers #include void main(){ int i = 3; int *j; int **k; j=&i; k=&j; printf(" %d ",**k); } Explanation: Memory representation

20 Pointers Here 6024, 8085, 9091 is any arbitrary address, it may be different. Value of k is content of k in memory which is 8085 Value of *k means content of memory location which address k keeps. k keeps address Content of at memory location 8085 is 6024 In the same way **k will equal to 3. Short cut way to calculate: Rule: * and & always cancel to each other i.e. *&a = a So *k = *(&j) since k = &j *&j = j = 6024 And **k = **(&j) = *(*&j) = *j = *(&i) = *&i = i = 3

21 Pointers