ā‰” Menu

C Pointers Fundamentals Explained with Examples – Part I

Anybody who is working on Linux environment (not just developers), should understand the fundamentals of C programming language and write some basic C program.

This article is part of our ongoing series on C programming language.

The concept of pointers is one of the most powerful fundamentals of C/C++ language.

Through pointers a developer can directly access memory from his/her code which makes memory related operations very fast. But, as always, with great power comes great responsibility.

A developer has to very carefully make use of pointers in order to avoid some problems that can be nightmare to debug.

In this article we will study the very basic concept of pointers with examples in C language.

What are Pointers?

Different from other normal variables which can store values, pointers are special variables that can hold the address of a variable. Since they store memory address of a variable, the pointers are very commonly said to “point to variables”. Lets try to understand the concept.


As shown in the above diagram:

  • A normal variable ‘var’ has a memory address of 1001 and holds a value 50.
  • A pointer variable has its own address 2047 but stores 1001, which is the address of the variable ‘var’

How to Declare a Pointer?

A pointer is declared as :

<pointer type> *<pointer-name>

In the above declaration :

  1. pointer-type : It specifies the type of pointer. It can be int,char, float etc. This type specifies the type of variable whose address this pointer can store.
  2. pointer-name : It can be any name specified by the user. Professionally, there are some coding styles which every code follows. The pointer names commonly start with ‘p’ or end with ‘ptr’

An example of a pointer declaration can be :

char *chptr;

In the above declaration, ‘char’ signifies the pointer type, chptr is the name of the pointer while the asterisk ‘*’ signifies that ‘chptr’ is a pointer variable.

How to initialize a Pointer?

A pointer is initialized in the following way :

<pointer declaration(except semicolon)> = <address of a variable>

OR 

<pointer declaration> 
<name-of-pointer> = <address of a variable>

Note that the type of variable above should be same as the pointer type.(Though this is not a strict rule but for beginners this should be kept in mind).

For example :

char ch = 'c'; 
char *chptr = &ch; //initialize 

OR 

char ch = 'c'; 
char *chptr; 
chptr = &ch //initialize

In the code above, we declared a character variable ch which stores the value ‘c’. Now, we declared a character pointer ‘chptr’ and initialized it with the address of variable ‘ch’.

Note that the ‘&’ operator is used to access the address of any type of variable.

How to Use a Pointer?

A pointer can be used in two contexts.

Context 1: For accessing the address of the variable whose memory address the pointer stores.

Again consider the following code :

   char ch = 'c'; 
   char *chptr = &ch;

Now, whenever we refer the name ‘chptr’ in the code after the above two lines, then compiler would try to fetch the value contained by this pointer variable, which is the address of the variable (ch) to which the pointer points. i.e. the value given by ‘chptr’ would be equal to ‘&ch’.

For example :

char *ptr = chptr;

The value held by ‘chptr’ (which in this case is the address of the variable ‘ch’) is assigned to the new pointer ‘ptr’.

Context 2: For accessing the value of the variable whose memory address the pointer stores.

Continuing with the piece of code used above :

char ch = 'c';
char t;
char *chptr = &ch;
t = *chptr;

We see that in the last line above, we have used ‘*’ before the name of the pointer. What does this asterisk operator do?

Well, this operator when applied to a pointer variable name(like in the last line above) yields the value of the variable to which this pointer points. Which means, in this case ‘*chptr’ would yield the value kept at address held by chptr. Since ‘chptr’ holds the address of variable ‘ch’ and value of ‘ch’ is ‘c’, so ‘*chptr’ yeilds ‘c’.

When used with pointers, the asterisk ‘*’ operator is also known as ‘value of’ operator.

An Example of C Pointers

Consider the following code :

CODE :

 
#include <stdio.h> 

int main(void) 
{ 
    char ch = 'c'; 
    char *chptr = &ch; 

    int i = 20; 
    int *intptr = &i; 

    float f = 1.20000; 
    float *fptr = &f; 

    char *ptr = "I am a string"; 

    printf("\n [%c], [%d], [%f], [%c], [%s]\n", *chptr, *intptr, *fptr, *ptr, ptr);

    return 0; 
}

OUTPUT :

$ ./pointers 

 [c], [20], [1.200000], [I], [I am a string]

To debug a C program, use gdb. The above code covers all the common pointers. The first three of them are very trivial now to understand so lets concentrate on the fourth one. In the fourth example, a character pointer points to a string.

In C, a string is nothing but an array of characters. So we have no staring pointers in C. Its the character pointers that are used in case of strings too.

Now, coming to the string, when we point a pointer to a string, by default it holds the address of the first character of the string. Lets try to understand it better.

The string, ‘I am String’ in memory is placed as :

1001   1002    1003    1004   1005   1006   1007   1008   1009   1010
I      a       m       S      t      r      i      n      g      \0

Since characters occupy one byte each, so they are placed like above in the memory. Note the last character, its a null character which is placed at the end of every string by default in C. This null character signifies the end of the string.

Now coming back to the point, any character pointer pointing to a string stores the address of the first character of the string. In the code above, ‘ptr’ holds the address of the character ‘I’ ie 1001. Now, when we apply the ‘value of’ operator ‘*’ to ‘ptr’, we intend to fetch the value at address 1001 which is ‘I’ and hence when we print ‘*ptr’, we get ‘I’ as the output.

Also, If we specify the format specifier as ‘%s’ and use ‘ptr’ (which contains the starting address of the string), then the complete string is printed using printf. The concept is that %s specifier requires the address of the beginning byte of string to display the complete string, which we provided using ‘ptr’ (which we know holds the beginning byte address of the string). This we can see as the last print in the output above.

Pointers as Structure Objects

Consider the following code :

CODE:

#include<stdio.h> 

struct st{ 
int a; 
char ch; 
}; 

int main(void) 
{ 
    struct st obj; 
    struct st *stobj = &obj; 

    stobj->a = 5; 
    stobj->ch = 'a'; 

    printf("\n [%d] [%c]\n", stobj->a, stobj->ch); 
    return 0; 
}

OUTPUT:

$ ./pointers 

 [5] [a]

In the above code, we have declared a pointer stobj of type ‘struct st’. Now since the pointer type is a structure, so the address it points to has to be of a ‘struct st’ type variable(which in this case is ‘obj’). Other interesting part is how structure elements are accessed using pointer variable ‘stobj’. Yes, When dealing with pointer objects, its a standard to use arrow operator -> instead of ‘.’ operator(which would have been used, had we used ‘obj’ to access the structure elements).

To conclude, In this article we studied the concept of pointers in C from scratch and then slowly built upon our understanding to more complex topics like using pointers as structure objects. This was a basic tutorial, we will cover more complex pointer concepts in the part-II of this article. (Part 2: Advanced C pointers).

Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! ā€“ 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • jalal hajigholamali December 5, 2011, 4:08 am

    Hi,

    Very useful article
    thanks a lot

  • renjith December 5, 2011, 7:40 am

    very nice article
    Go agead and explain us the double and triple pointers
    and 2D and 3D pointers
    Array V/s Pointers
    2D array V/s double pointers
    Can we replace array by pointers?
    main applications of pointers
    Function pointers. etc
    I can also help you guys if you need something..Lets make this more useful to programmers.

  • mikeeve December 5, 2011, 12:55 pm

    Good intro. If readers are interested, a much more in-depth discussion can be found in “Expert C Programming: Deep C Secrets” by Peter van der Linden, but, as the name suggests, it is not for beginners.

  • Himanshu December 5, 2011, 11:53 pm

    Thanks a lot for you valuable comments!!
    If people are interested, I can write a PART-II for this article too… šŸ™‚

  • phpweb December 6, 2011, 1:06 am

    Good one. Nice to read and learn

  • rpark December 7, 2011, 11:12 am

    Please DO a part-II.
    Your examples are good, but your explanations of the examples are the good stuff.
    Thanks

  • noone December 8, 2011, 8:12 am

    thanks. especially the describing images are nice to learn

  • apol January 9, 2012, 4:08 pm

    I really hope the part II won’t be in 2013 šŸ˜‰
    BUT, ok, it’s lot of work, so let’s take it easy and wait for a wonderfull part 2 !

  • Himanshu January 9, 2012, 8:36 pm

    @apol
    Part-II will arrive this month only. šŸ™‚

  • apol January 10, 2012, 1:59 am

    @Himanshu
    Thanks, I look forward to the second and well illustrated part of this article !

  • Anonymous February 2, 2012, 2:02 am

    very very useful tutorial

  • DESHRAJ SHARMA February 22, 2012, 8:24 pm

    in pointer can we assigh any pointer name to adress of array .
    ex: ptr=&a;
    2)
    what is mean by below statement in pointer
    ptr=&a[i]

    plese tell me that in a pointer what is mean by below statement
    ptr=&p[i];

  • DarkVenger March 27, 2012, 5:31 am

    @ DESHRAJ SHARMA

    With ptr = &a[i], ptr will have the address of the i element of vector a. In other words, you’re making ptr point to some character of vector a.
    Your code ptr = &a should be ptr = &a[0].
    Assuming a has “I am a string”, from the example above, ptr = &a[7] would print you only the string word.

    If you understand vectors, just think that a[i] is in fact *(a + i), this reads as “the value of the memory address a plus (incremented by) i”.

  • ujwal v June 10, 2012, 11:03 pm

    very quick guide fr pointer,,tnks fr using all data types in very first program itself to explain,that avoids many confusion

  • Mohan June 21, 2012, 10:16 am

    nice yar….

  • saranya July 2, 2012, 5:35 am

    please send simple examples for pointer

  • Himanshu July 5, 2012, 10:01 pm

    @saranya
    What kind of examples you need?

  • Anonymous July 11, 2012, 3:09 am

    **a refers to what?

  • Himanshu July 11, 2012, 9:50 am

    @Anonymous

    ‘a’ refers to an address
    ‘*a’ refers to the value kept at above address
    ‘**a’ In case the above value is an address then this refers to the value kept at above address

    I hope this helps!!!!!

  • mehta smit July 11, 2012, 11:32 pm

    gud onw šŸ™‚

  • neha sharma July 22, 2012, 8:26 am

    i think there is a mistake in one example of prog. there is missing * sign in ptr in 2nd example of prog.

  • Arun August 10, 2012, 6:42 am

    its so useful documrntry..

  • Karthick August 12, 2012, 11:08 am

    Helpful.
    Better examples.
    Pointer to pointers may be explained.

  • sreelakshmi prasad August 28, 2012, 3:49 am

    good example. the example should be much simple it is complecated to learners

  • selva madhesh September 15, 2012, 3:31 am

    i want to know how to perform assignment opearations in string and pointer

  • joshna negi September 20, 2012, 2:31 am

    it really helps me to understand.

  • mena September 30, 2012, 3:29 am

    nice example

  • HANNY NARANG October 1, 2012, 9:40 pm

    pointers is vry imp topic..n key point ……more or less ……i lyk to solv d xampl of pointrs …builtup an a code also…………………

    thnk u …………………

  • chap October 10, 2012, 6:08 pm

    Hello, great article, got a good idea about pointer dec & init. Furthur more can you explain me how to do this.
    I have
    uint8_t *C = malloc((5*sizeof(uint8_t));

    I want to do separately declare and initialize this; like this
    uint8_t *C;
    C= malloc((5*sizeof(uint8_t));

    can I do so? My requirement is declare *C in struct and after initialize it.

    thanks

  • kavya October 12, 2012, 12:52 pm

    thank you..!

  • Naresh October 14, 2012, 11:51 am

    nice one..! short and clear..!

  • kala October 15, 2012, 9:32 pm

    very nice explanation for the beginners.

  • sangeetha October 25, 2012, 9:16 am

    This helped me to revise before the day of my exam….. thanks.

  • MD RASHID October 29, 2012, 10:30 pm

    Very nice for beginners.

  • sarbi November 27, 2012, 6:46 am

    very nice….. easily understandable one……

  • Lokesh December 9, 2012, 4:43 am

    Good Example………………..

  • Anonymous December 9, 2012, 6:28 am

    its really very easy fr me to understand!!…better than my faculty!!!….:)

  • M.Silambarasan December 24, 2012, 10:58 am

    nice intro

  • jafar January 10, 2013, 1:08 pm

    It was excellent!Thanks

  • Mahaveer January 24, 2013, 9:31 pm

    Good explanation

  • veni January 28, 2013, 1:02 am

    its very useful to us

  • madhu January 29, 2013, 10:36 am

    its good way to learn

  • indhu January 30, 2013, 12:48 am

    such a wonderful explanation…………..,

  • ohed ali February 6, 2013, 10:33 pm

    hi frnds this is a wonderfull page..

  • Azhar February 13, 2013, 1:54 pm

    realy great!!

  • prateek February 21, 2013, 7:09 am

    really a nice one…….plzzz also give example of some programs

  • noor March 9, 2013, 1:24 am

    very useful things it is very easy to understands…….
    thanks a lot frnd……..

  • Vishnu March 24, 2013, 7:10 am

    Very nice coplecated

  • pantamsumith April 21, 2013, 11:52 pm

    good information about pointers…!!

  • josephnthyola May 9, 2013, 9:46 am

    good information about pointer. is good to know about pointers.

  • yash May 14, 2013, 10:01 pm

    excellent quick guide to pointers!!!!!!!!
    veryy well explained!!!

  • Murali Nimmala June 1, 2013, 5:57 am

    very very straight forward explanation.

  • mahadevi June 21, 2013, 3:07 am

    thanks ; it is very useful

  • Peter June 24, 2013, 10:00 pm

    How to use pointers in arrays

  • Sam July 10, 2013, 8:32 am

    Thanks,
    it was very helpful

  • shital parekh July 14, 2013, 11:16 am

    Really a good one

  • rahul saini July 21, 2013, 10:56 pm

    it is so eazy

  • Oviya July 29, 2013, 12:36 am

    Thanks….! it’s very usefull

  • yograj August 8, 2013, 11:39 am

    its good,,..

  • musni August 22, 2013, 11:30 am

    It’s really good to beginners……..

  • vigneswari August 30, 2013, 8:29 pm

    it is very useful for me

  • Anonymous September 4, 2013, 1:00 am

    it is very useful for allllll students

  • raviteja September 6, 2013, 10:34 am

    thanks @nice very useful for alllll students

  • Prashanth Rajagopalan September 8, 2013, 3:43 am

    Thanks a lot.. It helped me a lot to understand!!

  • chaitanya September 22, 2013, 12:56 am

    thanku .. ur exams are easy to understand

  • Sabyasachi September 27, 2013, 8:40 am

    This is very helpful to me, After all I gather some knowledge on Pointers.
    This will helpful for my further campussing too.
    thaks to u

  • Mohan October 3, 2013, 2:16 am

    it is easy to learn, thanks

  • kamala October 5, 2013, 8:18 pm

    thank u very much………………..

  • Prakash October 7, 2013, 6:53 pm

    nice explanation.
    1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
    I a m S t r i n g
    the sentence ‘i am string’ has space betn each words.
    what about the space?Space does not take memory address.Plz

  • Asad November 4, 2013, 7:33 am

    Thanx man this really helped.. Great stuff…

  • madhu kotika November 19, 2013, 1:11 am

    its very usefull thank u…………….

  • raghu silati December 1, 2013, 1:04 pm

    I need full details about constant character pointers and function pointers with examples

  • richa srivastava June 2, 2014, 11:53 am

    Its too good..I like the approach taken to explain…thnks a lot….

  • vignesh July 3, 2014, 3:24 am

    it is very easy to understand

  • Acou83 July 27, 2014, 6:11 pm

    Very good. Thank you!

  • Ashokkumar August 27, 2014, 4:55 am

    It is very helpful.
    Explain full details of pointer in c.

  • Aravind Reddy Solipuram December 22, 2014, 8:14 am

    can you explain how pointers when using arraysi.e., how pointers can point to array type variables

  • Bipasha Mandal February 27, 2015, 7:29 am

    it is too good and it is so easy to understand

  • danish rais March 9, 2015, 3:24 am

    your explanation and examples are so good .

  • Vinit Kulkarni March 26, 2015, 9:32 pm

    This is very helpful explanation about pointer
    thank you…..

  • saniya June 24, 2015, 2:22 am

    Thanks for this….it is very useful to us

  • ajay August 22, 2015, 11:33 pm

    It’s very nice for a Learner to write a c programme.

  • Bhavya September 25, 2015, 1:52 am

    Easy to understand

  • Anonymous November 16, 2015, 12:17 am

    its very useful

  • Ankababu GOWDA December 4, 2015, 2:51 am

    THANK YOU

  • Suresh December 15, 2015, 8:22 pm

    After reading this you will be my teacher. Thank you……..

  • suresh January 4, 2016, 8:02 am

    thanks a lot for this article every one easily understand the pointers concept…….

  • Anonymous January 5, 2016, 10:18 pm

    #include

    int main()

    {
    Ā 
    int i,j;
    Ā Ā Ā 
    int *p;

    i = 5;

    p = &i;

    j = *p;Ā 
    *p = 7;

    printf(ā€œ i = %d\nā€, i);
    printf(ā€œ j = %d\nā€, j);
    printf(ā€œ *p = %d\nā€, *p);

    return 0;

    }

    The output will be:
    i=7
    j=5
    *p=7

    #why the value of ‘i’ must be ‘7’ ? i very confused..please help me

  • Sandy January 8, 2016, 9:07 am

    Nice explaination

  • shiva March 1, 2016, 8:08 am

    very useful

  • Pete May 3, 2016, 8:56 pm

    At last! A basic pointers tutorial that explains the mechanics of strings with pointers. So many resources out there discussing the fundamental concepts of pointers but examples only use integers or single chars to illustrate. Those that do feature strings, often complicate the details by scoping in memory allocation and arrays unnecessarily. Thank you!

  • kumari July 3, 2016, 6:03 am

    simple and good

  • akshay December 27, 2016, 1:59 am

    Super explanation guys,hats off,keep on doin this good stuff

  • prashant January 5, 2017, 12:36 am

    nice content on this side. it helps me a lot.
    thank you. i am appreciate with your work.

  • David January 7, 2017, 3:02 pm

    Nice!

  • jayarathinam.p January 10, 2017, 12:31 am

    this article is very useful to me.so,I would like to say thank for that.

  • raghu r g January 17, 2017, 9:52 am

    Useful

  • Rather Sartaj February 2, 2017, 5:50 am

    what is meant by operation on pointers and it’s fundamentals

  • rohith May 25, 2017, 11:15 pm

    its very nice,
    i need full detail about pointers