Friday, March 18, 2011

Program for Another Case Of Manipulating An Arrays Using Pointers with Explanation

Program


#include <stdio.h>

void printarr(int a[]);
void printdetail(int a[]);
void print_usingptr_a(int a[]);
main()
{
    int a[5];
    int *b;
    int *c;
    for(int i = 0;i<5;i++)
    {
        a[i]=i;
    }
    printarr(a);
    *b=2;            \\ A
    b++;             \\ B
    *b=4;            \\ C
    b++;
    *b=6;            \\ D
    b++;
    *b=8;            \\ E
    b++;
    *b=10;
    b++;
    *b=12;
    b++;
    a=c; //error     \\F
    printarr(a);


}
void printarr(int a[])
{
    for(int i = 0;i<5;i++)
    {
        printf("value in array %d\n",a[i]);
    }
}
void printdetail(int a[])
{
    for(int i = 0;i<5;i++)
    {
        printf("value in array %d and address is %16lu\n",a[i],&a[i]);
    }
}

void print_usingptr_a(int a[])
{

    for(int i = 0;i<5;i++)
    {
        printf("value in array %d and address is %16lu\n",*a,a); \\ F
        a++; // increase by 2 bytes         \\ G
    }
}

Explanation

1.You can assign a value at the location specified by b using statement A.

2.Using statement B, you can point to the next location so that you can specify a value at that location using statement C. Using this procedure, you can initialize 5 locations.

3.You cannot assign the starting memory location as given by statement F to access those elements because a is a pointer constant and you cannot change its value.

4.The function print_usingptr_a works correctly even though you are writing a++. This is because when you pass a as a pointer in an actual parameter, only the value of a is passed and this value is copied to the local variable. So changing the value in the local variable will not have any effect on the outside function.

No comments:

Post a Comment