C Tutorial – More on Pointers

In the previous C programming language tutorial we looked at the fundamentals of pointers. In this C tutorial we will look at some specifics of pointers.

Initialize a pointer

Before you can use a pointer in for instance a printf statement, you have to initialize the pointer.
The following example will not initialize the pointer:



	#include<stdio.h>

	int main(void) {
		int *ptr_p;
		printf("%d\n",*ptr_p);
                return 0;
	}

In this example we print the value that ptr_p points to. However, we did not initialize the pointer. In this case the pointer contains a random address or 0.

The result of this program is a segmentation fault, some other run-time error or the random address is printed.
The meaning of a segmentation fault is that you have used a pointer that points to an invalid address. In most cases, a pointer that is not initialized or a wrong pointer address is the cause of segmentation faults. The next example demonstrates the correct usage of pointers:



	#include<stdio.h>

	int main(void)	{
		int x;
		int *ptr_p;
		x = 5;
                ptr_p = &x;
		printf("%d\n", *ptr_p);
                return 0;
	}

Note: If you forget to place * (in front of the pointer) in the printf statement, you will print the address of integer x. (Try it!).

Pointers as function arguments

The C language is a “call by value” language, which means that the called function is given a copy of its arguments, and doesn’t know their addresses. (For example myfunction(x) call is given, the value of x is passed, not its address). This makes it impossible to change the value of x from the inside of the function (myfunction).

Note: With an array this is not a problem. If x is an array (char x[10]) then x is is an address anyway.

Take a look at the following example, which will illustrate the problem:



	#include<stdio.h>

	void swapping(int c, int d) {
		int tmp;
		tmp = c;
		c = d;
		d = tmp;
		printf("In function: %d %d\n", c , d);
	}

	int main(void) {
		int a,b;

		a=5;
		b=10;
		printf("input: %d %d\n", a, b);
		swapping(a,b);
		printf("output: %d %d\n", a, b);
                return 0;
	}

In the example the values of the parameters are swapped in the function swapping. But when the function returns nothing will happen. The result is that the values are not swapped. (Try it!).

Pointers can be used to get around the “call by value” restriction. In the next example we will use pointers to correct the problem:



	#include<stdio.h>

	void swapping(int *ptr_c, int *ptr_d) {
		int tmp;

		tmp = *ptr_c;
		*ptr_c = *ptr_d;
		*ptr_d = tmp;
		printf("In function: %d %d\n", *ptr_c , *ptr_d);
	}

	int main(void) {
		int a,b;

		a=5;
		b=10;
		printf("input: %d %d\n", a, b);
		swapping(&a,&b);
		printf("output: %d %d\n", a, b);
                return 0;
	}

Note: Don’t forget to replace “swapping(a,b);” for swapping(&a,&b);”.

Pointing to the same address

There is no limit on the number of pointers that can point to the same address.



	#include<stdio.h>

	int main() {
		int a;
		int *ptr_b , *ptr_c, *ptr_d;

		ptr_b = &a;
		ptr_c = &a;
		ptr_d = ptr_b;
		return 0;
	}

Note: The variable a now had four names: a, *ptr_b, *ptr_c and *ptr_d .

Pointers and arrays

The C language allows pointer addition and subtraction. Let’s take a look at this example:

char array[10];


char *ptr_toarray = &array[0];

In this example we declare an array with ten elements. Then we declare that the pointer *ptr_toarray is the same as array[0] (the same as the first element of the array). Now we could do the following (note the placing of the parentheses):


*(ptr_toarray + 2);

This is the same as array[2]. So you can see, the C language allows arithmetic’s. But remember to place the parentheses very carefully. ( *(ptr_toarray + 2); is something different then *(ptr_toarray) + 2; ).

Pointers and common errors

In this paragraph we will talk about some common errors that can occur with pointers.

1) Pointers that are not initialized
If a pointer is not initialized, a pointer will point to a random memory location. For example:


     int *A;
     *A = 5;

When we declare pointer A, it will point to a random memory address. The pointer could point to memory of program code space, system stack etc, etc. (We don’t know). Then we say *A = 5; the program will try to write the value five at the random location A is pointing to. The program may crash right away, run for an hour and crash, corrupt data or nothing will happen. The result cannot be predicted. So always initialize pointers.

2) Invalid pointer reference
We have two pointers, A and B. A is initialized and B is not. If we say “A=B;”, pointer A points
to a random memory address (remember B is not initialized). Now any reference to *p is now an invalid pointer reference.

3) NULL pointers: run-time error and segmentation fault
The NULL pointer has a reserved value in the C and C++ language (very often the value zero but not necessarily). It indicates that it refers to nothing. A NULL pointer should not be confused with an uninitialized pointer. Because it refers to nothing, an attempt to dereference a NULL pointer can cause a run-time error (or often in C programs a segmentation fault).

That’s all for this tutorial.

This entry was posted in C Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There are currently 32 responses to “C Tutorial – More on Pointers”

Why not let us know what you think by adding your own comment!

  1. anand on August 24th, 2011:

    ohh its great.. !!

  2. Ranjan Kaliya on August 26th, 2011:

    excellent man..you Rock!!
    this was really very very easy to understand the concept of pointers..
    good explanation. 🙂

  3. Ankit Srivastava on October 13th, 2011:

    it is so useful for the beginners.
    Good

  4. Keith Thompson on October 16th, 2011:

    The correct declaration for the main function in C is “int main(void)”, *not*, “void main()”. gcc warns about this for good reason. (Compilers might accept “void main()”, but they’re not required to; the behavior is undefined.)

    Please fix.

  5. admin on October 16th, 2011:

    @Keith Thompson: You are right. Made the changes on this page.

  6. Casey on November 8th, 2011:

    A great Resource for intro to C.

  7. ajay malik on July 14th, 2012:

    best undertanding for pointer

  8. sairam on July 22nd, 2012:

    char *ptr_toarray = &array[0];

    can any one tell why & is there before array[0] ?

  9. Hemant love on July 27th, 2012:

    nice

  10. SYED MEHER ALI SHAH on August 9th, 2012:

    loved your tutorial ….! 🙂

  11. maaz sheikh on August 19th, 2012:

    nice work 😉

  12. sat on August 28th, 2012:

    @sairam :

    Just consider ‘*’ equivalent to ‘value present at address’ and ‘&’ equivalent to ‘address of’ …u’d get the answer

  13. arti on October 15th, 2012:

    thank u sir…..

  14. preet on November 20th, 2012:

    thanku sirjii u really helped me a lotttt

  15. Ranga on January 9th, 2013:

    Suprb.

  16. Giri on January 17th, 2013:

    its nice and understandable… but i want more

  17. sahu on February 1st, 2013:

    thnks…vry well explanation of pointers
    plz also provide TUTORIAL ON =>>
    “POINTERS WITH ARRAY” and “POINTER WITH STRINGS”

  18. Bill on February 2nd, 2013:

    This was especially useful because you explained all the little details that make functions/pointers/variables work. I.e., using ‘*’ and ‘&’ where needed.

  19. uko on February 3rd, 2013:

    excellent, excellent ,excellent.
    you demystified pointers for my c exams tommorow.
    a very big thnk you.

  20. roya on February 8th, 2013:

    like!

  21. RIT on February 22nd, 2013:

    I am confused in the swapping example..

    when u write swapping(&a,&b) in the main fun, it means swapping(address of a, address of b);
    so, the address of a and b are the arguments which will be sent to the swapping function.
    Now, the swapping function is called
    void swapping(int *ptr_c, int *ptr_d)

    The address of a is assigned to *ptr_c and address of b is assigned to *ptr_d.
    How is that possible?????????????

    In other examples you have shown that first assign the address of the variable to the pointer variable and deference it later.
    for exaple: x = 5;
    ptr_p = &x;
    printf(“%d\n”, *ptr_p);

    why don’t you do the same thing while passing the address of a and b to the swapping function and then deference the pointer later.
    you are passing the address of a to *ptr_c and address of b to *ptr_d
    shouldn’t it be address of a to ptr_c and address of b to ptr_d and then deference later on.

    Would it possible for you to explain this.

    Thanks in advance!
    RIT

    p.s. your tutorials are very good. thanks for putting it for free.

  22. Pelzmaster on March 17th, 2013:

    @RIT
    He is not dereferencing the pointers in void swapping(int *ptr_c, int *ptr_d), he is defining them. For example look at the first example:
    #include

    int main(void) {
    int *ptr_p; <= in this line he is defining the pointer, like he does in the funktion
    printf("%d\n",*ptr_p);
    return 0;
    }

    Correct me, if i'm not right.

    Pelzmaster

  23. anjali on March 18th, 2013:

    it is really good.it is very useful to recollect pointers concept
    thank u very much..

  24. Badrajith on April 22nd, 2013:

    Your explanation for arithmetic operations is not working in VC++ Express 2012. Correct solution should be *(ptr_toarray) + 2;. For *(ptr_toarray + 2) VC++ shows the memory address (maybe 2 added to the address) of the *(ptr_toarray).

  25. Getahun on May 25th, 2013:

    it is very nice way of explaination for beginners,i realy like it.

  26. sahil on June 1st, 2013:

    great job!!!

  27. Mano on June 8th, 2013:

    thankx boss……….!

  28. vivek on June 29th, 2013:

    @badrajith

    *(ptr)+2=*ptr+2……it will give u the value at taht address +2
    whilst *(ptr+2) will give u some location (+2 to the previous location)

  29. Chance on July 2nd, 2013:

    Awesome!! Thanks

  30. durva on September 10th, 2013:

    superbbbbbb……tanks a lot sir

  31. Arjun on October 1st, 2013:

    Oh man that’s gr8 yaar..
    we rock
    teacher shocked…. :-!

  32. mahesh on November 13th, 2013:

    this is very nice tutorial for beginner.