Showing posts with label Pointers. Show all posts
Showing posts with label Pointers. Show all posts

Tuesday, 12 February 2013

C Programming: Pointers


In the simplest term pointer is a nearly integer variable which stores a memory address of a computer which may contain other variable or even another pointer.
If a variable contains address of another variable than it is said that first variable points to second. Pointer can also be represented as a reference to another variable but there is very subtle difference in the two statements which is mostly dependent upon situation and environment.
Pointer is generally of size of integer on the machine but it may be of different type which indicates the type of variable the pointer is pointing to decides pointers properties and behavior. 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 and if used incorrectly may lead to disasters including permanent machine damage.
Also it is important to note that all operation perform on pointers are done through two operators '*' (Star) and '&' (Ampercent). '&' is a unary operator that returns a memory address of a variable. '*' is complement of '&' and return value stored at a memory location stored in a pointer. '*' can interpreted as statement "at address" while '&' can be interpreted as statement "address of".
Pointer Arithmetic
Pointer arithmetic is quite different from normal arithmetic unless and until you are work on char type pointers, reason being they are 1 byte long under all environments.
Not all arithmetic operations are defined in pointers. You can increment them, decrement them, add and subtract integer values from them. You even can subtract two pointers.But you cannot add two pointers, multiply, divide,modulus them. You can not also add or subtract values other than integer.
Now pointer arithmetic may look a little weird but it has a deep sense attach to it.
Now consider a pointer X , its current value that address it is pointing to is 1000 (just assuming).We make another assumption about the size of the data types. Size of data type is machine dependent, for example int can be 16,32, or 64 bit long depending upon your machine.
Now if this X pointer is char type(assumed 1 Byte or 8Bit long) than X++ will have value 1001 and X-- will have value 999. Now if this X pointer is integer type (assumed 2 byte or 32 bit long) than X++ will have value 1002 and X-- will have value 998. Again if this X pointer is float type (assumed 4 Byte or 32Bit long) than X++ will have value 1004 and X-- will have value 9996. Also if this X pointer is double type(assumed 8 Byte or 64 Bit long) than X++ will have value 1008 and X-- will have value 992. Do you see the pattern here.
Reason is when you increment a pointer of certain base type it increase it value in such a way that it points to next element of its base type. If you decrement a pointer its value decrease in such a way that it points to previous value of its base type. So increment as well as decrement in fixed quanta of size of the base type.
You can add or subtract any integer value, in such case value of pointer get increase and decrease by the product of the value to be added or subtract and size of the base type.
Pointer of user defined types such as structures and union also increase by the quanta of their bit values which can be determined using sizeof operator.
Pointer arithmetic in C may look a bit strange but it is extensively used in programming and provides unmatched efficiency in performance of task such as accessing an array.
Declaring Pointer Variables
In C, every variable must be declared for its type. Since pointer variables contain addresses that belongs to a separate data type, they must declared as pointers before we user them. The declaration of pointer variable takes the following form
 
data_type *pointer_name



This tells the compiler three things about the variable pointer_name.


  1. The asterisk(*) tells that the variable pointer_name is a pointer variable
  2. pointer_name needs a memory address.
  3. pointer_name points to a variable of type data_type.

Initialization of Pointer Variables

Once a pointer variable has been declared we can use the assignment operator to initialize the variable. Example:

  1: int p; 
  2: int *q;  /*declaration */
  3: q = &p;  /*initialization*/

Sum of two matrices using two dimensional array in C

Matrix is the perfect example of two dimensional array. It has row and column. Row represents one dimension and column represents second dimension. For example matrix[4][5], it has 4 rows, each row consisting 5 elements i.e matrix[0] has 5 elements,    matrix[1] has 5 element and so on. In this example two matrices are added and result is displayed. Addition is done with corresponding elements of individual matrix i.e. matrix1[0][0] is added with matrix2[0][0]. The complete source code and output is given here….
Source Code
//Sum of two matrices using two dimensional array
#include<stdio.h>
#include<stdlib.h>
int main(){
    int matrix1[10][10], matrix2[10][10], sum[10][10], i, j, m,n,p,q;
    printf("Enter the order of first matrix: ");
    scanf("%d%d",&m,&n);
    printf("Enter the order of second matrix: ");
    scanf("%d%d",&p,&q);
    if(m!=p && n!=q){
        printf("Order of matrix did not matched!!");
        exit(0);
    }
    printf("Enter first matrix: \n");
    for(i = 0 ; i < m; i++){
        for(j = 0; j < n; j++)
            scanf("%d", &matrix1[i][j]);
    }
    printf("Enter second matrix: \n");
    for(i = 0 ; i < p; i++){
        for(j = 0; j < q; j++)
            scanf("%d", &matrix2[i][j]);
    }
    for(i = 0 ; i < m; i++){
        for(j = 0; j < n; j++)
            sum[i][j] = matrix1[i][j] + matrix2[i][j];
    }
    printf("The sum of the matrix is :\n");
    for(i = 0 ; i < m; i++){
        for(j = 0; j < n; j++){
            printf("%d", sum[i][j]);
            printf("\t");
        }
        printf("\n");
    }
    return 0;
}

Output

matrix

C Programming: Advantages and Drawbacks of Pointers

Advantages
Pointers are more efficient in handling arrays and data tables. They can be used to return multiple values from a function via function arguments. Pointers permit references to functions and thereby facilitating passing of functions as arguments to other functions. The use of po0inter arrays to character strings results in saving of data storage space in memory. pointers allow C to support dynamic memory management. Pointers provide an efficient tool for manipulating dynamic data structures such as structures, linked lists, queues, stacks and trees. Pointers reduce length and complexity of programs. They increases the execution speed and thus reduce the program execution time.
Disadvantages
Pointers have tremendous power but the power can swing both sides good and evil. Pointer if used incorrectly leads to very difficult to unearth bugs which will most probably make you go wild. Pointers are itself are not any trouble but the value they are storing can be. If it contains a incorrect value it can lead to disasters of massive magnitude when used.
When you use this incorrect pointer to read a memory location, you may be reading a incorrect garbage value which if unluckily accepted by your program as assumed correct value nothing can help you. Consider a scenario in banking in which any customers real account value is switched with this garbage value, he can become a millionaire or beggar in a second, or think that in a rocket launching software you use this incorrect value as launching angle and crashing the billion dollar masterpiece. These scenarios are just my imagination running wild but you cannot ignore the fact that they are possibility.
Now when you use this incorrect pointer to write a memory location you may be writing a unknown memory location. If you have a large memory in the system maybe you are using a unassigned memory but if that memory by any luck is a memory used by O.S. or Hardware and you are modifying it you maybe corrupting your Operating System software or damaging your hardware and their drivers. Also it is a possibility that you maybe using a memory location already in use by your software storing some essential data and you are unknowingly modifying it. You maybe writing over your own code and data.
Such bugs and errors created by the pointers may not show up immediately but come up later and it is at that time difficult to predict that it was the pointer to blamed.
Due to these drawbacks of pointers, Programming language like JAVA, C# cannot allow pointer operation.

Difference between array and pointer in C/C++

Pointer Array
1. A pointer is a place in memory that keeps address of another place inside
1. An array is a single, pre allocated chunk of contiguous elements (all of the same type), fixed in size and location.
2. Pointer can’t be initialized at definition.

2. Array can be initialized at definition. Example
int num[] = { 2, 4, 5}
3. Pointer is dynamic in nature. The memory allocation can be resized or freed later.
3. They are static in nature. Once memory is allocated , it cannot be resized or freed dynamically.
4. The assembly code of Pointer is different than Array
4. The assembly code of Array is different than Pointer.