shaadi.com

Searching...
Friday, 31 May 2013

C language Pointer Programs By Smith Solace


Pointers
**********
- Is a variable that contains an address
- This address is a location of another variable in memory
- The value of a pointer "points" to a variable
which may be accessed indirectly with the special pointer operators
* and & (both unary operator)
- The * operator (indirection operator)accessess the contents of
a variable whose address is the value of a pointer
The * can be remembered as "value at address"
- The & operator returns the address of a variable and
can be remembered as "the address of"

----------------
- A variable is declared by giving it a data type and a name (e.g. int k;)
- A pointer variable is declared by giving it a data type and a name
(e.g. int *ptr)
where the asterisk informs the compiler that the variable named ptr,
is a pointer variable
and
the data type informs the compiler what data type the pointer will
point to
(ptr will point to integer variable in the above case).

- Once a variable is declared, we can get its address by preceding
its name with the unary & operator, e.g. &k

- Assign the addresss of the variable to the pointer
ptr=&k;

- Asterisk (*) is the "dereferencing operator", and it is used as follows:
*ptr = 7; //assigns 7 to k via ptr
We can "dereference" a pointer, i.e. refer to the value of variable k,
it points to, by using the unary '*' operator.

- An "lvalue" of a variable is the memory address,
i.e. where it is stored in memory.
The "rvalue" of a variable is the value stored in that variable
(at that address).


- Addresses are always of unsigned type

- Bytes allocated for any pointer is 2 bytes
( b'coz address is always unsigned )

- Data_type of the pointer declares the data_type of value
the pointer will point to

----------------


Def: provides indirect means or way of accessing the value of a data item
---

Note : A simple unsigned variable can also store the address of any
----- location,but it is not a pointer.


Declaring pointers  :-
-------------------
data_type * pointer_name;

Precaution
----------
Make sure u'r pointer always points to correct type of data,
b'coz when u declare a pointer of type int , the compiler
then assumes that any address that the pointer will hold will
point to an integer variable.

eg:

void main()
{
float x=10,y; int *p;
clrscr();
p=&x;       // no compilation error
y=*p; // this code doesnot assign the value of x to y.
// as p is declared to be an integer pointer,
// only 2 bytes of information will be transferred to y,
// not the 4 bytes that normally makeup a floating point number.

printf("%f\t%f\t%f\n",x,y,*p);
printf("\n%u\t%u",&x,p);
getch();
}




//****************************************************************************

Pointers
--------
Summary of Pointer Arithematic
==============================
 Note: Same Arithematic rules applicable for decrement operator

 Pointer       Description
 Arithematic
 ---------       --------------------------------------------------

1 ptr++ ptr=ptr + sizeof(Data_Type)

Use original value of ptr
& then ptr is incremented after statement execution.

2 ++ptr ptr=ptr + sizeof(Data_Type)

Original ptr is incremented before execution of statement.

3   * ptr++      *(ptr++)

Retrive the content of the location pointed to by
pointer and then increment the pointer.

4   * ++ptr      *(++ptr)

Increment the pointer and then retrieve the content of the new
location pointed to by the pointer.

5  (*ptr)++ Retrieve content of the location pointed to by the ptr,then
increment content of the location pointed to by the pointer.

For pointer type content use pointer arithematic  else
use standard arithematic.

6  ++ *ptr      ++ (*ptr)

Increment the content of the location pointed to by ptr
depending on the type of the content.

//****************************************************************************

Pointers and Arrays

//****************************************************************************

Reference basically means passing the address of variable

int x[5];

x == &x[0] both same
The occurence of the array name without subscript is same as
the address of the zeroth element.
Array variable always points to the base address,
i.e. the address of the zeroth element.
Hence, array are also a type of static or constant pointers,
as it will always point to the base address of an array.


Declare And Initialize
-----------------------
in x[]={5,8,7};

int *p=&x[0];    or int *p=x; //Both are same assignment

printf("%d",*p);   // 5

p=&x[1]; printf("%d",*p);   // 8

Note:
-----------------------------------------------------------
1.  If int x[3]={5,2,4}; is declared, then
x++ or x-- or x=x+1 cannot be given with Arrays, as they
are constant pointers.

Where as Pointers are Dynamic, i.e it can
point to other location.


2.  int No[3]={11,5,12}, *p=No;
No[i] and p[i] are same but never use p[i] as here,
both No and p are acting like static pointers pointing to the
base address.


int x[5]={5,8,9,3,4};
Assume address for the elements of x array are as;
x[0]  -> 312
x[1]  -> 314
x[2]  -> 316
x[3]  -> 318
x[4]  -> 320

int *p=x; //both p and x are pointing to the same address i.e. 312

All the below expressions are same (when value of i is between 0 to 4)

p[i]
x[i]
*(&x[0]+i)
*(p+i)
*(x+i)

*p+3 [ As * has Higher precedence than + ,so *p  therefore *p->5+3=8]
*p+3   3 added to value pointed to by p
*(p+3) 3 added to address in  p


Scaning values
---------------------
float y,*ptr=&y;
scanf("%f",&y);        or scanf("%f",ptr);

void sort(int a[],int size) // subscript notation
or

void sort(int p,int size) // pointer notation
{
int *end=p+size; // 312+(5*2) = 322
int *beg=p; // store address of p
int flag,t;

for(p=beg;p<end;p++)
{
for(p=end-size;p<end;p++)
{
if(*p>*(p+1))
{
t=*p;
*p=*(p+1);
*(p+1)=t;
}
}
}

for(i=0;p<end;p++)
printf("%d",*p);   // to print values

}
void main()
{
int x[5],i;
for(i=0;i<5;i++)
{
printf("Enter num: ");
scanf("%d",&x[i]);
}

sort(x,5);
}


//*******************        2 D   Arrays And pointers  **********************


/* Pointer Expression          Variable            Value
-------------------           ---------           -----
* ( * p)                     p[0][0]              2
* ( * p + 1 )                p[0][1]              4
* ( * ( p + 1 ) )       p[1][0]              3
* ( * ( p + 1 ) + 1 )     p[1][1]              6
* ( * ( p + 1 ) + 1 ) +1   p[1][1]+1            7
 ---------------------------------------------------------------------------

*p => p[0] =>   p[0][0]  |    p[0][1]
|
*(*p)  |    *(*p+1)
------------------|-------------------
p[1][0]  |    p[1][1]
|
*(*(p+1))      |    *(*(p+1)+1)



float value[20][30],*p;
p      = & value [0][0];
p + 4  = & value [0][4];
p + 30 = & value [1][0];
30th element of value is first element in the second row b'coz
counting starts at 0 , so 30th element is value[1][0]

*/

void main()
{
int p[3][5]={ { 2,4,6,8,10 },
{ 3,6,9,12,15 },
{ 5,10,15,20,25 },
};
clrscr();
printf("* ( * p)                  =    p[0][0]   => %d\n",* ( * p));
printf("* ( * p + 1 )             =    p[0][1]   => %d\n",* ( * p + 1 ));
printf("* ( * ( p + 1 ) )         =    p[1][0]   => %d\n",* ( * ( p + 1 ) ));
printf("* ( * ( p + 1 ) + 1 )     =    p[1][1]   => %d\n",* ( * ( p + 1 ) + 1 ));
printf("* ( * ( p + 1 ) + 1 ) +1  =    p[1][1]+1 => %d\n",* ( * ( p + 1 ) + 1 ) +1);
getch();
}

//**************************************************************************
//      Pointers And 2D Array
//--------------------------------------------------------------------------

void main()
{
char nm[3][20];
int i;

// nm[0] => &nm[0][0]
// nm[1] => &nm[1][0]
// nm[2] => &nm[2][0]

for(i=0;i<3;i++)
{
flushall();
gets(nm[i]);
}
}


//*********************outputs************************
void main()
{
int p[3][5]={ { 2,4,6,8,10 },
{ 3,6,9,12,15 },
{ 5,10,15,20,25 },
};

int *ip,i=1;
clrscr();
for(ip=p;ip<=&p[2][4];ip++)

if(i<=5)
{  printf("%d\t",*ip); i++; }
else
{ i=1; printf("\n");ip--; }

getch();
}

void main()
{
int a[2][3]={{11,12,13},{14,15,16}};
int *ip,i,j;
clrscr();
for(ip=&a[0][0],i=0;i<2;++i)
{
for(j=0;j<3;++j)
{
printf("%d\t",*(*(a+i)+j) ); }   // printf("%d\t",*ip++);
printf("\n");}
getch();
}


//********************* OutPuts ******************

void main()
{
int num[]={1,2,3},*p;
for(p=num;p<&num[3];p++)
printf("%d\t",*p);
}
void main()
{
int x[]={1,2,3,4};
int i,j,k;
clrscr();
i=*(&x[0]);
j=x[i];
k=x[j];
printf("%d %d %d",i,j,k);   // 1 2 3
getch();
}
void main()
{
int a[]={127,35,94,407,52,175};
int*p=a;
clrscr();
printf("(*p+3)  %d\n",(*p+3));           // 130
printf("*(p+3)  %d\n",*(p+3));          // 407
printf("*(p+1)+3  %d\n",*(p+1)+3);      // 38
printf("++(*p)  %d\n",++(*p));         //128
getch();
}

void main()
{
int x[]={1,2,3,4},i;
clrscr();
printf("\n x+i is equal to &x[i] \n Prints address of Array elements \n");
printf("\nx+i\n");
for(i=0;i<4;i++)
{                                    // 0      1     2    3
printf("x+%d  %u\n",i,x+i); // 65518 65520 65522 65524
}
printf("\n&x[i]\n");
for(i=0;i<4;i++)
{            // 0      1     2    3
printf("&x[%d])  %u\n",i+0,&x[i]); // 65518 65520 65522 65524
}
getch();
}

 void main()
{
int x[]={1,2,3,4},i;
clrscr();
printf("*(x+i) is equal to *(&x[i]) and x[i]\n Prints contents of an array\n");
printf("\n*(x+i)\n");
for(i=0;i<4;i++)
{                                        //i      -> 0 1 2 3
printf("*(x+%d)  %d\n",i+0,*(x+i)); // *(x+i) -> 1 2 3 4
}
printf("\n*(&x[i])\n");
for(i=0;i<4;i++)
{                                            //i        -> 0 1 2 3
printf("*(&x[%d])  %d\n",i+0,*(&x[i])); // *(&x[i]) -> 1 2 3 4
}
printf("\nx[i]\n");
for(i=0;i<4;i++)
{                                          //i        -> 0 1 2 3
printf("x[%d]  %d\n",i+0,x[i]);          // x[i]     -> 1 2 3 4
}
getch();
}

void main()
{
int x[]={5,2,3,4},i;
clrscr();
printf("\n*x+i\nAdds value of i to x[0] ie 5\n");
for(i=0;i<4;i++)
{                                          //i        -> 0 1 2 3
printf("*x+%d  %d\n",i+0,*x+i);     // *x+i   -> 5 6 7 8
}
getch();
}

void main()
{
char s[]="C pointers",*p=s;
clrscr();
printf("s -> %s\np -> %s\n",s,p);
// C pointers
for(;*p!='\0';p++)   //  for(;*p;p++)
printf("p -> %s\n",p); // C pointers
//  pointers
// pointers
//--

// To get back the starting location

/* printf("%u",p);
printf(" %u",s);
printf(" %u %u",p-(sizeof(s)-1),p-strlen(s));*/

// p=s <=>  p=p-(sizeof(s)-1) <=> p=p-strlen(s))

for(p=p-(sizeof(s)-1);*p!='\0';p++)
printf("*p -> %c\n",*p);


getch();
}

0 comments:

Post a Comment