Presentation is loading. Please wait.

Presentation is loading. Please wait.

Pointers.

Similar presentations


Presentation on theme: "Pointers."— Presentation transcript:

1 Pointers

2 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.

3 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.

4 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

5 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.

6 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;

7 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)

8 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

9 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).

10 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.

11 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

12 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.

13 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 }

14 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 }

15 Pointer Operations

16 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)

17 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.

18 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.

19 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. }

20 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

21 Pointer Arithmetic int a=13; 2 bytes as a whole form the integer float q=2.3; float *s; s=&q; *s will give the value bytes form the float value Pointer variable ‘s’ will be assigned with the address of q. The address of q assigned will be 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

22 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.,

23 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

24 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.

25 Pointer Arithmetic Example of incrementing the float type pointer.
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

26 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) }

27 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.

28 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 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

29 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.

30 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.

31 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


Download ppt "Pointers."

Similar presentations


Ads by Google