Pointers in c

Post on 22-Jan-2016

239 views 2 download

Tags:

description

pointer in c

Transcript of 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.

Y ptr is pointing to memory address 100.

Pointer Declaration

• Syntax :- Datatype * identifier;

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’

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.

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.

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

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

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.

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.

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’