Pointers in c

14

description

pointer in c

Transcript of Pointers in c

Page 1: Pointers in c
Page 2: Pointers in c

• Pointers are widely used in programming; they are used to refer to memory location of another variable without using variable identifier itself. They are mainly used in linked lists and call by reference functions.

Page 3: Pointers in c

Y ptr is pointing to memory address 100.

Page 4: Pointers in c

Pointer Declaration

• Syntax :- Datatype * identifier;

Page 5: Pointers in c

1. #include <stdio.h>2. int main()3. {4. char a='b';5. char *ptr;6. printf("%c",a);7. ptr=&a;8. printf("%p",ptr);9. *ptr='d';10. printf("%c",a);

11. return 0;12. }

In line 4 we are declaring char variable called a; it is initialized to character ‘b’,

In line 5, the pointer variable ptr is declared.

In line 7, the address of variable a is assigned to variable ptr.

In line 9 value stored at the memory address that ptr points to is changed to ‘d’

Page 6: Pointers in c

Address operator

• Address operator (&) is used to get the address of the operand. For example if variable x is stored at location 100 of memory; &x will return 100.

Page 7: Pointers in c

Pointer arithmetic (Pointers and arrays)

• Pointers can be added and subtracted. However pointer arithmetic is quite meaningless unless performed on arrays. Addition and subtraction are mainly for moving forward and backward in an array.

Page 8: Pointers in c
Page 9: Pointers in c

1. #include <stdio.h>2. int main()3. {4. int ArrayA[3]={1,2,3};5. int *ptr;6. ptr=ArrayA;7. printf("address: %p - array value:%d n",ptr,*ptr);8. ptr++;9. printf("address: %p - array value:%d n",ptr,*ptr);

10. return 0;11. }

in line 4 we are declaring ‘ArrayA’ integer array variable initialized to numbers ‘1,2,3’,

In line 5, the pointer variable ptr is declared.

In line 6, the address of variable ‘ArrayA’ is assigned to variable ptr.

In line 8 ptr is incremented by

Page 10: Pointers in c
Page 11: Pointers in c

• Note: & notation should not be used with arrays because array’s identifier is pointer to the first element of the array.

Page 12: Pointers in c

Pointers and functions

• Pointers can be used with functions. The main use of pointers is ‘call by reference’ functions. Call by reference function is a type of function that has pointer/s (reference) as parameters to that function. All calculation of that function will be directly performed on referred variables.

Page 13: Pointers in c

Pointer to Pointer

• Pointers can point to other pointers; there is no limit whatsoever on how many ‘pointer to pointer’ links you can have in your program.

Page 14: Pointers in c

Char *ptrA;Char x=’b’;Char *ptrb;ptrb=&x;ptrA=&ptrb;

• ptrA gives 100, *ptrA gives 101 , ptrb is 101 ,*ptrb gives b, **ptrA gives b

• comment: **ptrA means ‘value stored at memory location of value stored in memory location stored at PtrA’