Exforsys.com
 
Home Tutorials C Language
 

C Programming - Pointers

 

C Programming - Pointers

In this tutorial you will learn about C Programming - Pointers, Pointer declaration, Address operator, Pointer expressions & pointer arithmetic, Pointers and function, Call by value, Call by Reference, Pointer to arrays, Pointers and structures, Pointers on pointer.


Introduction:

In c a pointer is a variable that points to or references a memory location in which data is stored. Each memory cell in the computer has an address that can be used to access that location so a pointer variable points to a memory location we can access and change the contents of this memory location via the pointer.


Pointer declaration:

A pointer is a variable that contains the memory location of another variable. The syntax is as shown below. You start by specifying the type of data stored in the location identified by the pointer. The asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the variable.


type * variable name

Example:


int *ptr;
float *string;


Address operator:

Once we declare a pointer variable we must point it to something we can do this by assigning to the pointer the address of the variable you want to point as in the following example:


ptr=#


This places the address where num is stores into the variable ptr. If num is stored in memory 21260 address then the variable ptr has the value 21260.


/* A program to illustrate pointer declaration*/

main()
{
int *ptr;
int sum;
sum=45;
ptr=∑
printf (“\n Sum is %d\n”, sum);
printf (“\n The sum pointer is %d”, ptr);
}


we will get the same result by assigning the address of num to a regular(non pointer) variable. The benefit is that we can also refer to the pointer variable as *ptr the asterisk tells to the computer that we are not interested in the value 21260 but in the value stored in that memory location. While the value of pointer is 21260 the value of sum is 45 however we can assign a value to the pointer * ptr as in *ptr=45.


This means place the value 45 in the memory address pointer by the variable ptr. Since the pointer contains the address 21260 the value 45 is placed in that memory location. And since this is the location of the variable num the value also becomes 45. this shows how we can change the value of pointer directly using a pointer and the indirection pointer.

/* Program to display the contents of the variable their address using pointer variable*/

include< stdio.h >
{
int num, *intptr;
float x, *floptr;
char ch, *cptr;
num=123;
x=12.34;
ch=’a’;
intptr=&x;
cptr=&ch;
floptr=&x;
printf(“Num %d stored at address %u\n”,*intptr,intptr);
printf(“Value %f stored at address %u\n”,*floptr,floptr);
printf(“Character %c stored at address %u\n”,*cptr,cptr);
}


Pointer expressions & pointer arithmetic:

Like other variables pointer variables can be used in expressions. For example if p1 and p2 are properly declared and initialized pointers, then the following statements are valid.


y=*p1**p2;
sum=sum+*p1;
z= 5* - *p2/p1;
*p2= *p2 + 10;


C allows us to add integers to or subtract integers from pointers as well as to subtract one pointer from the other. We can also use short hand operators with the pointers p1+=; sum+=*p2; etc.,
we can also compare pointers by using relational operators the expressions such as p1 >p2 , p1==p2 and p1!=p2 are allowed.

/*Program to illustrate the pointer expression and pointer arithmetic*/
#include< stdio.h >
main()
{
int ptr1,ptr2;
int a,b,x,y,z;
a=30;b=6;
ptr1=&a;
ptr2=&b;
x=*ptr1+ *ptr2 –6;
y=6*- *ptr1/ *ptr2 +30;
printf(“\nAddress of a +%u”,ptr1);
printf(“\nAddress of b %u”,ptr2);
printf(“\na=%d, b=%d”,a,b);
printf(“\nx=%d,y=%d”,x,y);
ptr1=ptr1 + 70;
ptr2= ptr2;
printf(“\na=%d, b=%d”,a,b);
}


Pointers and function:

The pointer are very much used in a function declaration. Sometimes only with a pointer a complex function can be easily represented and success. The usage of the pointers in a function definition may be classified into two groups.
1. Call by reference
2. Call by value.


Call by value:

We have seen that a function is invoked there will be a link established between the formal and actual parameters. A temporary storage is created where the value of actual parameters is stored. The formal parameters picks up its value from storage area the mechanism of data transfer between actual and formal parameters allows the actual parameters mechanism of data transfer is referred as call by value. The corresponding formal parameter represents a local variable in the called function. The current value of corresponding actual parameter becomes the initial value of formal parameter. The value of formal parameter may be changed in the body of the actual parameter. The value of formal parameter may be changed in the body of the subprogram by assignment or input statements. This will not change the value of actual parameters.

/* Include< stdio.h >
void main()
{
int x,y;
x=20;
y=30;
printf(“\n Value of a and b before function call =%d %d”,a,b);
fncn(x,y);
printf(“\n Value of a and b after function call =%d %d”,a,b);
}

fncn(p,q)
int p,q;
{
p=p+p;
q=q+q;
}


Call by Reference:

When we pass address to a function the parameters receiving the address should be pointers. The process of calling a function by using pointers to pass the address of the variable is known as call by reference. The function which is called by reference can change the values of the variable used in the call.

/* example of call by reference*?

/* Include< stdio.h >
void main()
{
int x,y;
x=20;
y=30;
printf(“\n Value of a and b before function call =%d %d”,a,b);
fncn(&x,&y);
printf(“\n Value of a and b after function call =%d %d”,a,b);
}

fncn(p,q)
int p,q;
{
*p=*p+*p;
*q=*q+*q;
}


Pointer to arrays:

an array is actually very much like pointer. We can declare the arrays first element as a[0] or as int *a because a[0] is an address and *a is also an address the form of declaration is equivalent. The difference is pointer is a variable and can appear on the left of the assignment operator that is lvalue. The array name is constant and cannot appear as the left side of assignment operator.


/* A program to display the contents of array using pointer*/
main()
{
int a[100];
int i,j,n;
printf(“\nEnter the elements of the array\n”);
scanf(“%d”,&n);
printf(“Enter the array elements”);
for(I=0;I< n;I++)
scanf(“%d”,&a[I]);
printf(“Array element are”);
for(ptr=a,ptr< (a+n);ptr++)
printf(“Value of a[%d]=%d stored at address %u”,j+=,*ptr,ptr);
}


Strings are characters arrays and here last element is \0 arrays and pointers to char arrays can be used to perform a number of string functions.


Pointers and structures:

We know the name of an array stands for the address of its zeroth element the same concept applies for names of arrays of structures. Suppose item is an array variable of struct type. Consider the following declaration:

struct products
{
char name[30];
int manufac;
float net;
item[2],*ptr;


this statement declares item as array of two elements, each type struct products and ptr as a pointer data objects of type struct products, the


assignment ptr=item;


would assign the address of zeroth element to product[0]. Its members can be accessed by using the following notation.


ptr- >name;
ptr- >manufac;
ptr- >net;


The symbol - > is called arrow pointer and is made up of minus sign and greater than sign. Note that ptr- > is simple another way of writing product[0].


When the pointer is incremented by one it is made to pint to next record ie item[1]. The following statement will print the values of members of all the elements of the product array.


for(ptr=item; ptr< item+2;ptr++)
printf(“%s%d%f\n”,ptr- >name,ptr- >manufac,ptr- >net);


We could also use the notation


(*ptr).number


to access the member number. The parenthesis around ptr are necessary because the member operator ‘.’ Has a higher precedence than the operator *.


Pointers on pointer:

While pointers provide enormous power and flexibility to the programmers, they may use cause manufactures if it not properly handled. Consider the following precaustions using pointers to prevent errors. We should make sure that we know where each pointer is pointing in a program. Here are some general observations and common errors that might be useful to remember.

A pointer contains garbage until it is initialized. Since compilers cannot detect uninitialized or wrongly initialized pointers, the errors may not be known until we execute the program remember that even if we are able to locate a wrong result, it may not provide any evidence for us to suspect problems in the pointers.



The abundance of c operators is another cause of confusion that leads to errors. For example the expressions such as


*ptr++, *p[],(ptr).member


etc should be carefully used. A proper understanding of the precedence and associativity rules should be carefully used.



Read Next: C Programming - Dynamic Memory allocation



 

 

Comments


zsk_00 said:

  excellent introduction to pointers!
June 11, 2006, 6:46 pm

ADF said:

  How can u access to double pointer if in the Struct have double pointer..
for Exmpl:
typedef struct Student
{
int id;
char*name;
int numSubject;
char**subjectsEnrolledIn;
}Student;
#endif

I want to access to "char**subjectsEnrolledIn" for my main code..
April 10, 2007, 4:57 pm

PriyaKKTer said:

  I guess u can access it this way;

**student.subjectsenrolledin;

U can access *name using

*student.name;

hence accessing subjectsenrolledin must be this way.....

**student.subjectsenrolledin;
May 28, 2007, 2:11 am

sekarbala123 said:

  you had did a very good job
June 29, 2007, 1:43 pm

billy said:

  can u please give me some examples of programs which arrange input rumble numbers from lowest to highest number.
August 21, 2007, 8:08 pm

Chibu sankala said:

  hove to access triple pointer using dynamic memory allocation
August 30, 2007, 7:30 am

Raj Kumar Sanpui said:

  I think the material on pointers is good only for beginners, but for people who have worked quiet for some time on C, may not find it too useful.
October 19, 2007, 2:28 am

Raj Kumar Sanpui said:

  int i=1,j=0
i=(i ) ( i);
k=(i ) ( i);
October 19, 2007, 2:31 am

C said:

  program under Address operator,

intptr=&x; should have been

inptr=#
October 29, 2007, 8:45 pm

enjelmar said:

  who can tell me the work of c programmers?is it practical to concentrate mastering c language?if i graduated knowing how to use c language and assembly language what job can i apply for??...........answer me at art_pioneer_07@yahoo.com......thanks a lot^^
December 5, 2007, 8:38 am

kiranMantripragada said:

  Can any one clarify my doubt:
can we perform substraction on two pointers which belongs to two diff arrays.
for eg:int a[5]={23,43,55,67,89};
int b[5]={11,44,55,77,88},*i,*j;
i=&a[0];
j=&b[3];
printf("%d",i-j);
im getting result 4 dis.how do it possible.
January 11, 2008, 1:47 am

Madhava-> said:

  See, i & j are pointers as per your declaration.
This means i & j hold addresses and not values.

Now when you do i-j it is subtracting the addresses and hence you are getting that value.

You need to do *i - *j or better (*i) - (*j) would give proper results.

Yes you can do arithmetic operations on different pointers as long as they are of same type. That is int.
February 7, 2008, 7:13 am

sony said:

  can u please give me some examples of programs for ANOVA(Analysis of variance) calculation using pointers.
May 1, 2008, 4:27 am

meghasahni said:

  can u pls explain me the use of pointers in linked list
September 30, 2008, 11:20 am

nitin said:

  can you tell me how many * in possible before any variable or
what is the length of pointer to pointer in c programing
November 11, 2008, 12:01 am

PANKAJ DWIVEDI said:

  it's good i like it very much
November 28, 2008, 6:58 am

jhobhelle said:

  can u explain the use of pointers????
January 11, 2009, 5:52 am

satya said:

  hi.....in the second program the value of intptr will be &num..
u r taking the value wrong...
January 15, 2009, 2:00 pm

Taka said:

  It is actual use of the pointer.
<pre><code>
#include <stdio.h>
#define MAZ 10
#define ZERO 0
static int ap[MAZ]={1,2,3,4,5,6,7,8,9,10};
int main(void){
int ia,*cp,sum=ZERO;
for(cp=&ia,ia=ZERO;ia<5;ia++){
sum+=ap[ia];
sum+=ap[*cp+5];
}
printf("sum=%d",sum);
return ZERO;
}
<pre><code>
July 12, 2009, 2:39 am

shoujoreader said:

  I don't get it, why I always see using void in main, and return at the end. That's not really necessary, the program will still compile and run without it.

or maybe I'm still, a beginner.
August 20, 2009, 11:55 pm

Vishnu said:

  Hi, Using Void in main(void) is no harm, it is ok if u don't use, but we have to use return to return a int value (it is depends on the type u use as return type). if we don't return then we will get waring while we compile , which is not recommended.
September 10, 2009, 3:44 pm

vikas said:

  what is typecasting ?
char **p;
(char *)*p
are these two different??
November 1, 2009, 2:40 pm

jenis said:

  struct Student
{
int id;
char*name;
int numSubject;
char**subjectsEnrolledIn;
}*S1;
so how can we access member of struct student *s1;
November 19, 2009, 11:27 am

Cheshar said:

  You can access it in this way :

s1->id = 1;
s1->name = "Rachit";
s1->numsubject = 2;
s1->(*subjectsEnrollment) = "Any string that you want to enter";

But one thing that you should take care of is that you should allocate memory for the structure before accessing its elements.
December 12, 2009, 6:38 pm

rohit said:

  distinguish between (*a)[6] and *a[6]
December 13, 2009, 1:45 am

SoniaSingh said:

  Can I subtact a pointer from another pointer?

char *fptr,*lptr;
lptr= lptr-fptr; //subtaction

Is this possible?

December 13, 2009, 10:12 am

isha said:

  Yes, you can subtract pointer from a pointer.
January 5, 2010, 2:00 pm

Shweta said:

  Can someone give me a program
1.To find if a given triangle is equilateral using structures?
2.Bank accounts using structures in C
Please. I'm in class 11 and have my lab exam tomorrow.
February 3, 2010, 7:10 am

Post Your Comment:

Members Please Login
Your Name:*
e-mail ID:(required for notification)*
Image Verification: 
 
 Subscribe    

Sponsored Links

 

Subscribe via RSS


Get Daily Updates via Subscribe to Exforsys Free Training via email


Get Latest Free Training Updates delivered directly to your Inbox...

Enter your email address:


 

Subscribe to Exforsys Free Training via RSS
 

 
Partners -  Privacy and Legal Policy -  Site News -  Contact   Sitemap  

Copyright © 2000 - 2010 exforsys.com. All Rights Reserved

Page copy protected against web site content infringement by Copyscape