Pointers.

Slides:



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

UNIT 9: Pointers Data Variable and Pointer Variable Pass by Reference
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:
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.
Pointer. Warning! Dangerous Curves C (and C++) have just about the most powerful, flexible and dangerous pointers in the world. –Most other languages.
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. Topics Pointers Pointer Arithmetic Pointers and Arrays.
Pointers Applications
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Introduction to Pointers.. What is a pointer? A derived type which holds the address of a variable. Simply a memory location where the variable is stored.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
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:
Pointers *, &, array similarities, functions, sizeof.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU Status 6/10/2016 Initial content copied verbatim from ECE 103 material developed.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
Lecture 5 Pointers 1. Variable, memory location, address, value
Dynamic Allocation in C
CS1010 Programming Methodology
EGR 2261 Unit 11 Pointers and Dynamic Variables
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
UNIT 5 C Pointers.
Pointers.
Introduction to Linked Lists
Chapter 7 - Pointers Outline 7.1 Introduction
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Java Primer 1: Types, Classes and Operators
Pointers in C.
Student Book An Introduction
Programmazione I a.a. 2017/2018.
Lecture 6 C++ Programming
Introduction to Linked Lists
Pointers and References
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Pointers and Arrays S.Bhuvaneshwari Assistant Professor/CSE
Object Oriented Programming COP3330 / CGS5409
Instructor: Ioannis A. Vetsikas
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter-3 Operators.
Outline Defining and using Pointers Operations on pointers
Introduction to Problem Solving and Programming
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Pointer Operations.
Chapter 3 Operators and Expressions
Overloading functions
Pointers Pointers point to memory locations
Pointer Variables A pointer is a variable that contains a memory address The address is commonly the location of another variable in memory This pointer.
Data Structures and Algorithms Introduction to Pointers
Java Programming Language
OPERATORS in C Programming
Expressions An Expression is a sequence of operands and operators that reduces to a single value. An operator is a language-specific syntactical token.
Pointers and pointer applications
OPERATORS in C Programming
Introduction to Pointers
Presentation transcript:

Pointers

Introduction Variable and data type: A "normal variable" is a location in memory that can hold a value. It is nothing but the naming convention to refer the address in which the value gets stored. Data type determines the no of bytes allocated to the data. Memory location: Each memory location is identified and referenced with an address. The address in which the data gets stored. For int data type, two bytes get allocated. The starting byte’s address will be returned as the address of the variable.

Pointer Introduction Pointer Variable: The variable which holds the address. A pointer is a variable that points to another variable. A pointer "points to" that other variable by holding a copy of its address. In the simplest term pointer is a nearly integer variable which stores a memory address. Declaration: Syntax: data type * pointervariableName; data type – Refers to the data type of the value that is stored in the address the pointer points to. It can be of any type (i.e) int, float, char, struct etc., * - Denotes the declared variable is a pointer. It is used to differentiate the normal variable from the pointer variable. PointervariableName – The naming conventions applicable to the normal variable applies here also.

The Operators The & and * operators: Both are unary operators & - Address of operator - It returns the address of the variable * - Indirection (or) dereference (or) Value at address operator main() { int a; a=2; printf(“Address of a %u”, &a); printf(“Value at address of a %d”, *(&a)); } Output: Address of a 65435 Value at address of a 2

Pointer Expression Normal Variable declaration : char a; Pointer Variable declaration : char *a, *b; In the above declaration, Char – The value stored in the address the pointer holds is of char data type a - Pointer variable name; More than one pointer variable can be declared in the same line. All of same type. Why pointer variable is declared with data type? Even though the pointer is just an integer, the data type is used to determine the type of data it points to. So that it can retrieve the value stored in the address, the pointer points to. Note: The type of variable the pointer is pointing to decides pointers properties and behavior. In the declaration, data type * will give the variable the special attention that it is a pointer variable. To make an ordinary variable to be a pointer variable, * is added between the data type and variable name.

Pointer Assignments Initialization of Pointer variable: Assigning value to the pointer variable. (i.e) address. & in front of a variable will retrieve the address of the variable. main() { int a; a=2; printf(“Address of a %u”, &a); printf(“Value at address of a %d”, *(&a)); } Output: Address of a 65435 Value at address of a 2 printf(“Address of a %u”, p); printf(“Value at address of a %d”, *p); int *p; p=&a; int *p=&a; a=2; *p=2;

Pointer Assignment Variable Type Value Address a int 2 65435 &a - p 65432 &p *p *(&a) Variable Type Value Address a Int 3 65435 &a - p Int * 65432 &p *p int *(&a)

Pointer Assignment Notes: a a is assigned value 2 65435 3 2 As ‘p’ is having address of a, *p retrieves value of ‘a’ *p *(&a) 3 2 p (&a) Address of ‘a’ is assigned to ‘p’. 65432 65435

Pointer Assignment Pointer variable can be assigned to another pointer variable. int *r, *k, h; r=&h; k=r; Now r, k both point to same location(i.e) address of h. Uninitialized Pointer: int *r, h; printf(“%d”,*r); // will result in error Uninitialized pointers can point to any memory location. Using * (indirection operator) on uninitialized pointers may result in program throwing a run time error. Using a pointer without initializing it to any data may result in data corruption or even program crash. Make sure you initialize all pointers to a valid address before dereferencing them. Pointer variable not assigned with any value(Address).

Pointer Assignment Invalid Pointer References: Zero Pointer Reference: An invalid pointer reference occurs when a pointer's value is referenced even though the pointer doesn't point to a valid block. p=q; when q is uninitialized. The pointer p will then become uninitialized as well, and any reference to *p is an invalid pointer reference. Zero Pointer Reference: A zero pointer reference occurs whenever a pointer pointing to zero is used in a statement that attempts to reference a block. For example, if p is a pointer to an integer, the following code is invalid: int *p; p = 0; *p = 12; There is no block pointed to by p. Therefore, trying to read or write anything from or to that block is an invalid zero pointer reference. Dereferencing such a pointer, however, is invalid.

Pointer Assignment The data type of the variable and the type of pointer which holds the address of the variable must be same. int r; char *h, g; h=&r; // Wrong h=&g; // Correct Do not initialize the pointer variable with normal values. Even though it is an integer, it is used to hold the address value. int *r, h; r=2; // Wrong *r=2; // Correct

Pointer Assignment main() { float age; float *adAge; adAge=&age; printf(“No of bytes of pointer variable %d\n”, sizeof(adAge)); printf(“No of bytes of value pointer points to %d”, sizeof(*adAge)); printf(“No of bytes of variable %d”, sizeof((age)); } Output: No of bytes of pointer variable: 2 No of bytes of value pointer points to: 4 No of bytes of variable : 4 sizeof pointer variable: Pointer variable always holds address value only. Hence always the size will be 2 bytes. This is platform dependent. The size of pointer variable doesn’t depend on the data type of the value it points to.

Pointer Assignment Null Pointer: Null pointer is a pointer which points to nothing. Pointer can be declared NULL if it cannot be initialized at the beginning and the value is initialized during execution. Or assign zero to pointer variable. When a pointer is declared, an uninitialized pointer is set to NULL. It points to the base address of CPU register and since register is not addressable, usage of a null pointer will lead to crash or at minimum a segmentation fault. Depending on the compiler the value varies. Most of the cases it will be zero. main() { int *r, h; r=NULL; // r=0; printf(“Address the pointer holds %u :“, r); // Compiler dependent printf(“Value the pointer points to %d:”, *r); // Program crashes }

Pointer Assignment void Pointer: void pointer technically is a pointer which is pointing to the unknown. Also in dynamic memory allocation function such as malloc ( ) and alloc ( ) returns void pointer which can be easily converted to other types.(Will dealt later) As the data the pointer points to is not known, dereferencing void pointer will result in error. main() { int h; void *r; r=&h; printf(“size of pointer variable %d :”, sizeof(r)); // Compiler dependent printf(“size of value pointer points to %d:”, sizeof(*r)); // Program crashes }

Pointer Operations

Type Casting Type Casting: Converting the data type of one variable into another data type. Syntax: (data type to be converted to) variable; Eg: float a = 2.3; int b; b=(int)a; Types: Implicit Conversion: int float double (small no of bytes higher no of bytes) Explicit Conversion: double float int (higher no of bytes small no of bytes)

Pointer Conversions Converting pointer from one type to another: Pointer of one type cannot be implicitly converted from one type to another but can be explicitly converted using type casting. In such a conversion a pointer always assumes that it is point to a object of its type but reality may differ. Syntax: (data type to be converted to *) variable; int *p; (char *)p; Normal variable cannot be converted to pointer variable using type casting. Pointer variable of one type can be type casted to another type.

Pointer Conversions Notes: Type conversion is a powerful feature but yet it may difficult to remove bugs and crashes and should be used with uttermost vigilance. It may also lead to unexpected and unreliable results but program would compile successfully. While typecasting one pointer to another because even after type casting the pointer can point to anything but it will still think it is pointing to something of it declared type and have properties of the original type. void pointer can be used for this purpose. As the void pointer doesn’t point to any type of data, it can be type casted to any type, and results in no error.

Pointer Conversions Example program to convert the pointer from pointing to int to char data type. main() { int i = 10; char *p1; int *p2; p2 = &i; p1 = (char *) p2; // Type Casting and Pointer Conversion printf (" *p1 = %c And *p2 = %d", *p1,*p2); // Output will be depending upon the compiler. }

Pointer Conversions Example program to convert the pointer from pointing to void to char data type. main() { int i = 10; int *p1; void *p2; p2 = &i; p1 = (int *) p2; // Type Casting and Pointer Conversion printf (" *p1 = %d And *p2 = %d", *p1,*p2); } Output: *p1 = 10 And *p2 = 10

Pointer Arithmetic int a=13; 2 bytes as a whole form the 65345 65346 integer float q=2.3; float *s; s=&q; *s will give the value 2.3 4 bytes form the 23456 25457 25458 25459 float value Pointer variable ‘s’ will be assigned with the address of q. The address of q assigned will be 23456. As the given type is float, *s will take the value as a whole from four bytes. 8 bits 8 bits 8 bits 8 bits 8 bits 8 bits

Pointer Arithmetic Notes: When the address of a variable is assigned to a pointer variable, only the starting byte’s address will be stored. According to the data type the no of bytes from the starting bytes will be taken account. If the data type is not proper, pointer variable will not be knowing till which byte the data is stored. The arithmetic operations performed on the pointer variable, it must be applied such that it is able to retrieve the whole value whether it is an integer or float or char etc.,

Pointer Arithmetic When a pointer of certain base type is increased, it increases its value in such a way that it points to next element of its base type. If a pointer of certain base type is decremented, its value decreases in such a way that it points to previous value of its base type. Increment as well as decrement in fixed quanta of size of the base type. Pointer value can be incremented or decremented only by integer as it is holding the address. Two forms of pointer arithmetic: Pointer + integer Pointer – pointer (Will dealt later while dealing with array and pointers

Pointer Arithmetic Unary Pointer Arithmetic Operators: Pointer variable ++; Adds sizeof(datatype) number of bytes to pointer, so that it points to the next entry of the datatype. The no of bytes is determined by the data type of the value the pointer variable is pointing to. Pointer variable --; Subtracts sizeof(datatype) number of bytes to pointer, so that it points to the next entry of the datatype.

Pointer Arithmetic Example of incrementing the float type pointer. 23456 23457 23458 23459 23460 23461 23462 ------- 4 bytes form the float value Incrementing the pointer will make the pointer to point to starting of next 4 bytes main() { float a = 2.3, *b=&a; printf(“Address of á’ stored in b:”, b); printf(“Value stored in a:”, *b); printf(“Incrementing the pointer variable: ”, ++b); printf(“Value retrieved after incrementing:”, *b); } Output: Address of á’ stored in b: 23456 Value stored in a: 2.3 Incrementing the pointer variable: 23460 Value retrieved after incrementing: // Not known. Will be retrieved at the execution time. 8 bits 8 bits 8 bits 8 bits 8 bits 8 bits 8 bits

Pointer Arithmetic main() { int *ptrn; int a; float *ptrflt; float b; ptrn=&a; ptrflt=&b; ptrn++; //increments by sizeof(int) (2 bytes) ptrflt--; //increments by sizeof(long) (4 bytes) }

Pointer Arithmetic Arithmetic Operations between a pointer and an integer: Pointer + integer Pointer Variable + n is valid, if n is an integer. The result is the following: Pointer Variable + (n*sizeof(data type of the value pointer points to)) It advances the pointer by n number of size of data type. Pointer Variable - n is similar. The result will be: Pointer Variable - (n*sizeof(data type of the value pointer points to)) It decrements the pointer by n number of size of data type.

Pointer Arithmetic Eg: float h=4.6, *ptrf; ptrf=&h; If h is stored at address 23454, then ptrf will be having the address value 23454 stored in it. Pointer Increment Value Incremented Pointing address Value retrieved ptrf - 23454 4.6 ptrf+1 // ptrf++ ptrf+(1*sizeof(float)) 23458 Points to the next four bytes starting from 23458 ptrf+2 ptrf+(2*sizeof(float)) 23462 Points to the next four bytes starting from 23462 ptrf+3 Ptrf+(3*sizeof(float)) 23466 Points to the next four bytes starting from 23466

Pointer Arithmetic Notes: Arithmetic operations addition (or) subtraction of an integer value can be done on a pointer. Multiplication, Division, Modulus by an integer cannot be done on a pointer. This will give the error Illegal use of a pointer in function main. Addition of two pointers cannot be done. This will give the error Invalid pointer addition.

Pointer Comparison Pointer variable can be compared only with another pointer. Comparison can be done using <, >, ==, <= and >= operators. When two pointers are compared, actually the address they are holding is compared. Using ‘==’ operator on pointers, will check whether both pointers being compared are pointing to the same address or not If pointer a and pointer b are holding the same address, then a==b will be true. Otherwise false. The use arithmetic operations and the comparisons will be having wide space when the pointer is applied to array. A pointer can be checked whether it is pointing to NULL using the ‘==’ (Equal to) operator int *p=NULL; if(p==0 ) will return true.

Pointer Comparison Valid Comparisons: Comparing same type pointers. Comparing pointers pointing to same location. Comparison can be done to check for NULL pointer Invalid Comparisons: Comparing pointer and a normal variable. // Compiler Error Comparing different type of pointers. Such as comparing char pointer with int or some other type of pointer. // Warning