You are on page 1of 11

10/20/2010

Home Tut orials Software Testing Programing

C Programming - Pointers
Dat a Management Cert ificat ion Career Cent er Skill Test Forums Int erview Quest ions

Search
Sponsored Links

Home

Tutorials

C Language

Sponsored Links

C Programming - Pointers
C Language Tutorials

TSR in C - An Int roduct ion Concept of Pixel in C Graphics Call by Value and Call by Reference C Language - The Preprocessor C Programming - File management in C C Programming - Linked List s C Programming - Dynamic Memory allocat ion C Programming - Pointers C Programming - St ruct ures and Unions C Programming - Functions (Part -II) C Programming - Functions (Part -I) C Programming - Handling of character string C Programming - Arrays C Programming - Decision Making - Looping C Programming - Decision Making - Branching C Programming - Managing Input and Output Operat ions C Programming - Expressions C Programming - Operators C Programming - An Overview C Programming - Constants and Variables

Category: C Language Read: 247693 | Comment s (72)

Share

Tweet

C Programming - Pointers
In this tutorial you will learn about C Programming - Pointers, Pointer declaration, Address operator, Pointer expressions & pointer arithmetic, Pointers and func tion, Call by value, Call by Referenc e, Pointer to arrays, Pointers and struc tures, Pointers on pointer.

Introduction:
In c a pointer is a variable that points to or references a memory loc ation in which data is stored. Eac h memory c ell in the c omputer has an address that c an be used to acc ess that location so a pointer variable points to a memory loc ation we can ac cess and change the contents of this memory location via the pointer.

This site is blocked by PE

URL: http://www.fac

Pointer declaration:
A pointer is a variable that c ontains the memory loc ation of another variable. The syntax is as shown below. You start by spec ifying the type of data stored in the loc ation identified by the pointer. The asterisk tells the c ompiler that you are c reating a pointer variable. Finally you give the name of the variable. type * variable name Example: int *ptr; float *string;
Subscribe via RSS

Get Daily Updates via


Get Latest Free Training Updates delivered directly to your Inbox... Enter your email address:

Address operator:
Onc e we dec lare 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=&num; This plac es 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 c an also refer to the pointer variable as *ptr the asterisk tells to the c omputer that we are not interested in the value 21260 but in the value stored in that memory loc ation. 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 plac e the value 45 in the memory address pointer by the variable ptr. Since the pointer c ontains the address 21260 the value 45 is plac ed in that memory loc ation. And since this is the location of the variable num the value also bec omes 45. this shows how we c an change the value of pointer direc tly using a pointer and the indirec tion pointer. /* Program variable*/ include< { int num, float x, char ch, num=123; x=12.34; to display the contents of the variable their address using pointer

Subscribe

stdio.h > *intptr; *floptr; *cptr;

exforsys.com/tutorials//c-pointers.html

1/11

10/20/2010

C Programming - Pointers
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 c an 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 subtrac t one pointer from the other. We c an also use short hand operators with the pointers p1+=; sum+=*p2; etc ., we c an also compare pointers by using relational operators the expressions suc h 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 muc h used in a func tion dec laration. Sometimes only with a pointer a complex func tion can be easily represented and suc cess. The usage of the pointers in a function definition may be c lassified into two groups. 1. Call by referenc e 2. Call by value.

Call by value:
We have seen that a func tion is invoked there will be a link established between the formal and ac tual parameters. A temporary storage is created where the value of actual parameters is stored. The formal parameters pic ks up its value from storage area the mec hanism of data transfer between actual and formal parameters allows the ac tual parameters mec hanism of data transfer is referred as c all by value. The c orresponding formal parameter represents a local variable in the c alled func tion. The c urrent value of c orresponding ac tual parameter becomes the initial value of formal parameter. The value of formal parameter may be c hanged in the body of the actual parameter. The value of formal parameter may be c hanged in the body of the subprogram by assignment or input statements. This will not change the value of ac tual 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 func tion the parameters receiving the address should be pointers. The proc ess of c alling a func tion by using pointers to pass the address of the variable is known as c all by referenc e. The func tion which is c alled by reference can c hange the values of the variable used in the c all.

exforsys.com/tutorials//c-pointers.html

2/11

10/20/2010

C Programming - Pointers
/* 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 c an dec lare 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 c onstant and c annot 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 c harac ters arrays and here last element is \0 arrays and pointers to c har arrays c an 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 c onc ept applies for names of arrays of struc tures. Suppose item is an array variable of struc t type. Consider the following dec laration: 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 c alled arrow pointer and is made up of minus sign and greater than sign. Note that ptr- > is simple another way of writing produc t[0]. When the pointer is inc remented by one it is made to pint to next rec ord 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 acc ess the member number. The parenthesis around ptr are nec essary bec ause the member operator . Has a higher prec edence than the operator *.

exforsys.com/tutorials//c-pointers.html

3/11

10/20/2010
Pointers on pointer:

C Programming - Pointers
While pointers provide enormous power and flexibility to the programmers, they may use c ause manufac tures if it not properly handled. Consider the following prec austions 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 c ommon errors that might be useful to remember. A pointer c ontains garbage until it is initialized. Sinc e c ompilers cannot detec t uninitialized or wrongly initialized pointers, the errors may not be known until we execute the program remember that even if we are able to loc ate a wrong result, it may not provide any evidenc e for us to suspec t problems in the pointers. Sponsored Links The abundanc e of c operators is another c ause of c onfusion that leads to errors. For example the expressions suc h as *ptr++, *p[],(ptr).member etc should be c arefully used. A proper understanding of the prec edence and assoc iativity rules should be c arefully used.

Tweet

Share

Read Next: C Programming - Dynamic Memory allocat ion

Related Topics
Subconscious Mind Programming Conscious Mind Programming Concepts of Object -Oriented Programming C++ Pointers Neuro-linguist ic Programming Methods

Search

Comments
zsk_00 said: excellent introduc tion to pointers
Ju ne 11, 2006, 6:46 pm

A DF said: How c an u acc ess to double pointer if in the Struc t have double pointer.. for Exmpl: typedef struct Student { int id; c har*name; int numSubjec t; c har**subjectsEnrolledIn; }Student; #endif I want to ac cess to "c har**subjec tsEnrolledIn" for my main c ode..
Apri l 10, 2007 , 4:57 pm

Priy aKKTer said: I guess u c an ac c ess it this way; **student.subjec tsenrolledin; U can ac cess *name using *student.name; hence ac cessing subjectsenrolledin must be this way..... **student.subjec tsenrolledin;

exforsys.com/tutorials//c-pointers.html

4/11

10/20/2010
Ma y 28, 2007, 2:11 a m

C Programming - Pointers
sekarbala1 23 said: you did a very good job
Ju ne 29, 2007, 1:43 pm

billy said: c an u please give me some examples of programs whic h arrange input rumble numbers from lowest to highest number.
Au gu st 21, 2007 , 8:08 pm

Chibu sankala said: hove to ac cess triple pointer using dynamic memory alloc ation
Au gu st 30, 2007 , 7 :30 a m

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=&num;
October 29, 2007 , 8:45 pm

enjelmar said: who c an tell me the work of c programmers?is it practic al to c onc entrate mastering c language?if i graduated knowing how to use c language and assembly language what job c an i apply for??...........answer me at art_pioneer_07@yahoo.c om......thanks a lot^^
December 5, 2007, 8:38 a m

kiranMantripragada said: Can any one c larify my doubt: c an we perform substrac tion on two pointers whic h 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.
Ja nu ar y 11, 2008, 1:47 a m

Madhav a-> said: See, i & j are pointers as per your dec laration. This means i & j hold addresses and not values. Now when you do i-j it is subtrac ting the addresses and henc e 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.
Febr ua ry 7, 2008, 7 :13 a m

sony said: c an u please give me some examples of programs for ANOVA(Analysis of varianc e) c alc ulation using pointers.
Ma y 1, 2008, 4:27 a m

meghasahni said: c an u pls explain me the use of pointers in linked list


Septem ber 30, 2008, 11:20 am

nitin said:

exforsys.com/tutorials//c-pointers.html

5/11

10/20/2010

C Programming - Pointers
c an you tell me how many * in possible before any variable or what is the length of pointer to pointer in c programing
Novem ber 11, 2008, 12:01 a m

PA NKAJ DWIVEDI said: it's good i like it very much


Novem ber 28, 2008, 6:58 a m

jhobhelle said: c an u explain the use of pointers????


Ja nu ar y 11, 2009, 5:52 a m

saty a said: hi.....in the second program the value of intptr will be &num.. u r taking the value wrong...
Ja nu ar y 15, 2009, 2:00 pm

Taka said: It is ac tual use of the pointer. <pre><code> #inc lude <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[*c p+5]; } printf("sum=%d",sum); return ZERO; } <pre><code>
Ju ly 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 nec essary, the program will still c ompile and run without it. or maybe I'm still, a beginner.
Au gu st 20, 2009, 11:55 pm

V ishnu 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 c ompile , which is not rec ommended.
Septem ber 10, 2009, 3:44 pm

v ikas said: what is typecasting ? c har **p; (c har *)*p are these two different??
Novem ber 1, 2009, 2:40 pm

jenis said: struct Student { int id; c har*name; int numSubjec t; c har**subjectsEnrolledIn; }*S1; so how c an we ac c ess member of struct student *s1;
Novem ber 19, 2009, 11:27 am

Cheshar said: You c an ac c ess 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 c are of is that you should allocate memory for the structure

exforsys.com/tutorials//c-pointers.html

6/11

10/20/2010

C are of is that you Pointers But one thing that you should take cProgramming - should allocate memory for the structure before ac c essing 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 subtac t a pointer from another pointer? c har *fptr,*lptr; lptr= lptr-fptr; //subtac tion Is this possible?

December 13, 2009, 10:12 a m

isha said: Yes, you c an subtrac t pointer from a pointer.


Ja nu ar y 5, 2010, 2:00 pm

Shweta said: Can someone give me a program 1.To find if a given triangle is equilateral using struc tures? 2.Bank ac c ounts using struc tures in C Please. I'm in c lass 11 and have my lab exam tomorrow.
Febr ua ry 3, 2010, 7 :10 a m

arjumand said: tell reason of using pointer in programming


Ma rch 3, 2010, 6:52 a m

Debasish Pati said: does TURBO C++ 4.5 SUPPORT NAMESPACE


Ma rch 8, 2010, 12:59 pm

sudhir jaiswal said: {int *p,*q,i; q=(int *)200; p=(int *)100; what is the meaning of this?
Ma rch 13, 2010, 6:42 a m

gaurav kumar said: use of func tion in C++


Apri l 22, 2010, 6:52 a m

gaurav kumar said: how to use of while loop in C language.


Apri l 22, 2010, 6:53 a m

Jeya said: It is very simple, we can use while loop for the the number of generation rather than using the for loop. Syntax: while(Condition) { Statements; } We can inc rement or dec rement the value inside the c ondition loop.
Apri l 24, 2010, 8:29 a m

richa said: how do we define string pointer in to func tion?


Ma y 10, 2010, 9:04 a m

rks said: i want more ex. of ptr


Ma y 16, 2010, 10:44 pm

exforsys.com/tutorials//c-pointers.html

7/11

10/20/2010
imam said:

C Programming - Pointers
how to define pointer into linked list
Ma y 17 , 2010, 8:04 a m

indrajith said: what is the use of void using inside the main fuc tion.ex.int main(void)
Ma y 21, 2010, 3:48 a m

rakesh said: How memory is alloc ated?


Ma y 23, 2010, 1:53 a m

farhan khan said: Write a program named c ount letters that c ounts the occ urrenc es of all small and capital letters in given below string and then prints the result in the format (Caps, count:: Small, c ount).Strings is bc AdBDeCEad and it should print this result (Caps, 5:: Small, 5).The program should take address of the sourc e string as a parameter via stac k and also provide proper c omments against eac h instruc tion. plz explain with code?? help me soon plz reply
Ma y 25, 2010, 10:55 a m

anoos said: Write a program to do integer arithmetic add two thousand digit numbers.
Ju ne 4, 2010, 9:37 a m

Fausto said: What does this mean? *ptr << 1


Ju ne 7, 2010, 3:13 pm

fiza said: If we dec lare a pointer like; *j; j=&a; printf("%u=",j); and then inc rement or dec rement in the j and print it. what will b the output? as it will print the adresses, will be the addresses print regularly ac c ording to the increment or dec rement or not plz give me answer in detail plz
Ju ne 22, 2010, 3:26 pm

addy l said: Hi,i want a C OR java program using call by referenc e that adds twos numbers.plz help me. thanx.
Ju ne 29, 2010, 4:20 am

friend for all said:

the differenc e between [*a][6] and *a[6] is that ,in the first c ase the entire array is not a pointer,but in sec ond c ase the array a is dec lared as a pointer
Ju ly 4, 2010, 2:15 a m

friend for all said:

Include< stdio.h > void main() { int x,y; x=20; y=30; printf(n Value of a and b before function c all =%d %d,a,b); fncn(&x,&y); printf(n Value of a and b after function c all =%d %d,a,b); } fncn(p,q) int p,q; { *p=*p+*p; *q=*q+*q; }
Ju ly 4, 2010, 2:17 a m

nisarg said:

exforsys.com/tutorials//c-pointers.html

8/11

10/20/2010
Ju ly 4, 2010, 5:11 am

C Programming - Pointers
It is amazing site and we c an learn more.

deepu said: Read the book "LET US C" by Yeshavant Kanethkar it's amazing for beginners.
Ju ly 6, 2010, 10:23 am

raghav endra said: c an you please implement this c har(*(*x[3])())[5]


Ju ly 15, 2010, 5:24 am

A nitha said: Its very informative


Ju ly 17 , 2010, 7:32 am

ramkumar said: How to give input and get output of a variable whose data type is not known?
Ju ly 25, 2010, 2:51 am

surjeet said: how we c an use double pointers


Ju ly 31, 2010, 10:14 pm

gaurav gpel said: c an we write like this: int arr[10]; int *p=arr[7];/*valid or invalid*/
Au gu st 8, 2010, 3:32 pm

ok said: yes , you c an perform this ... gaurav gpel


Au gu st 23, 2010, 2:02 pm

marimuthu said: Good and Thank you for this information.


Septem ber 4, 2010, 1:45 am

chittem said: int i=5,*p; c an i give the base address 'i' for pointer base address like &p=&i; whic h is possible are not pls reply
Septem ber 13, 2010, 2:16 a m

sankar said: Excellent introduc tion to pointers


Septem ber 15, 2010, 2:52 a m

ritu said: inc lude< stdio.h > { int num, *intptr; float x, *floptr; c har c h, *c ptr; num=123; x=12.34; c h=a; intptr=&x; c ptr=&c h; floptr=&x; printf(Num %d stored at address %un,*intptr,intptr); printf(Value %f stored at address %un,*floptr,floptr); printf(Charac ter
Septem ber 18, 2010, 12:40 am

kathir said: If anybody know the pgm to build a heap using fun to pntr and pntr to struc ture?
Septem ber 19, 2010, 2:23 a m

A bhishek Y eola said:

exforsys.com/tutorials//c-pointers.html

9/11

10/20/2010

C Programming - Pointers
Thank You RITU mam..I might sc ore an A grade in C language this time in my college(BITS Pilani, Goa Campus) :) I got a D last semester :(
Septem ber 20, 2010, 12:58 am

muhammad tahir said: Salam to all, the given programs are very good,but some problems has not solve c orrec tly.
Septem ber 20, 2010, 8:10 a m

selvam said: ok....not bad.... so that its not enough .....


Septem ber 25, 2010, 9:23 a m

pushpender soni said: C is general purpose language c is also helpful for coding the software but pointer plays a very powerful role in C.
Septem ber 30, 2010, 2:26 a m

A bhishek Y eola said: @Muhammad tahir I dont agree with your c omments...whatever Ritu Mam has solved is c orrec t(Thank You mam :)). I finally secured good marks this time(2nd overall :)). BITSIAN
Septem ber 30, 2010, 3:05 pm

Subodh Kolhe said: Hey guyz Can some one answer this question: c an we use triple or further quadrupled pointers? reply asap-exam tom :( and nic e comment Pushpender
Septem ber 30, 2010, 3:15 pm

rav i said: hi, I have question.... #inc lude<c onio.h> void main() { int j;c har k;float f=5;c lrsc r(); for(k=1;k<10;k++) f-=.1; printf("nf=%g",f); getc h(); } Well, I want to know the reason behind the output.spec ially,after 6th iteration,f=4.4000001 and so forth.So,plz c an anyone reply here.
October 2, 2010, 4:42 pm

ashish said: @ravi... It gives c orrec t output after 6th iteration it gives 4.4 whic h c ompiler are you using.Try Visual C++ 6.
October 5, 2010, 12:59 am

A bu Bakarr Dukuray said: I really enjoy the tutorial.


October 6, 2010, 4:35 a m

kashisj said: Hey plz help me I don't understand the use of **i; like pointers what ac tually they give.
October 12, 2010, 3:00 am

Sakaria said: What are the advantages and advantages of using pointers in programming in C++?

exforsys.com/tutorials//c-pointers.html

10/11

10/20/2010
October 13, 2010, 10:41 a m

C Programming - Pointers
ashu said: How to initialize a pointer variable?
October 13, 2010, 12:06 pm

A afi said: Good tutorial. One c an also refer Pointers in C by Yeshwant Kanetkar for pointers.
October 18, 2010, 3:32 am

Post Your Comment:


Members Please Login

Your Name:*

e-mail ID:(require d for notifica tio n) *

Image Verification:

Subscribe

Submit

Partners - Privacy and Legal Policy - Sit e News - Cont act


Copyright 2000 - 2010 exforsys.com. All Rights Reserved

Sit emap

exforsys.com/tutorials//c-pointers.html

11/11

You might also like