Tutorial - Understanding Pointers in C - Part 2


Submit solution

Points: 0
Time limit: 3.0s
Memory limit: 64M

Author:
Problem type
Allowed languages
C

Tutorial

This is the second part of the tutorial on Pointers in C. Please read Part 1 before continuing this tutorial.

Compiled from multiple sources on the internet.

C - Pointers Continued

Direct and Indirect Access Pointers

In C, there are two equivalent ways to access and manipulate a variable content

  • Direct access: we use directly the variable name

  • Indirect access: we use a pointer to the variable

Let's understand this with the help of program below

#include <stdio.h>

int var = 1; /* Declare and initialize an int variable */

int *ptr; /* Declare a pointer to int */

int main( void )
{
ptr = &var;     /* Initialize ptr to point to var */

printf("\nDirect access, var = %d", var);           /* Access var directly and indirectly */
printf("\nIndirect access, var = %d", *ptr);       /* Display the address of var two ways */

printf("\n\nThe address of var = %d", &var);
printf("\nThe address of var = %d\n", ptr);       /*change the content of var through the pointer*/

*ptr=48;
printf("\nIndirect access, var = %d", *ptr);
return 0;
}

After compiling the program without any errors, the result is:

Direct access, var = 1
Indirect access, var = 1

The address of var = 4202496
The address of var = 4202496

Indirect access, var = 48

Pointers Arithmetic

The pointer operations are summarized in the following figure

Pointers Arithmetic

Priority operation (precedence)

When working with pointers, we must observe the following priority rules:

  • The operators * and & have the same priority as the unary operators (the negation!, the incrementation++, decrement--).
  • In the same expression, the unary operators *, &,!, ++, - are evaluated from right to left.

If a P pointer points to an X variable, then * P can be used wherever X can be written.

The following expressions are equivalent:

int X =10

int *P = &Y;

For the above code, below expressions are true

Expression    Equivalent Expression

Y=*P+1          Y=X+1

*P=*P+10        X=X+10

*P+=2           X+=2     

++*P            ++X

(*P)++      X++

In the latter case, parentheses are needed: as the unary operators * and ++ are evaluated from right to left, without the parentheses the pointer P would be incremented, not the object on which P points.

The arithmetic and basic operation that can be used when dealing with pointers are mentioned below.

  • Assignment - int P1,P2 P1=P2; P1 and P2 point to the same integer variable
  • Incrementation and decrementation - Int *P1; P1++;P1-- ;
  • Adding an offset (Constant) - This allows the pointer to move N elements in a table. The pointer will be increased or decreased by N times the number of byte (s) of the type of the variable. P1+5;

Pointers and Arrays

Traditionally, we access the array elements using its index, but this method can be eliminated by using pointers. Pointers make it easy to access each array element.

#include <stdio.h>
int main()
{
    int a[5]={1,2,3,4,5};   //array initialization
    int *p;     //pointer declaration
               /*the ptr points to the first element of the array*/

    p=a; /*We can also type simply ptr==&a[0] */

    printf("Printing the array elements using pointer\n");
    for(int i=0;i<5;i++)    //loop for traversing array elements
    {
            printf("\n%x",*p);  //printing array elements
            p++;    //incrementing to the next element, you can also write p=p+1
    }
    return 0;
}

Output

1
2
3
4
5

Adding a particular number to a pointer will move the pointer location to the value obtained by an addition operation. Suppose p is a pointer that currently points to the memory location 0 if we perform following addition operation, p+1 then it will execute in this manner.

Pointer Incrementation/Addition

Pointers and Strings

A string is an array of char objects, ending with a null character '\ 0'. We can manipulate strings using pointers. Here is an example that explains this section

#include <stdio.h>
#include <string.h>
int main()
{
char str[]="Hello Program";
char *p;
p=str;
printf("First character is:%c\n",*p);
p =p+1;
printf("Next character is:%c\n",*p);
printf("Printing all the characters in a string\n");
p=str;  //reset the pointer
for(int i=0;i<strlen(str);i++)
{
printf("%c\n",*p);
p++;
}
return 0;
}

Output

First character is:H
Next character is:e
Printing all the characters in a string
H
e
l
l
o

P
r
o
g
r
a
m

Another way to deal strings is with an array of pointers like in the following program:

#include <stdio.h>
int main()
{
  char *materials[ ] = {  "iron",  "copper",  "gold"};
  printf("Please remember these materials :\n");
  int i ;
  for (i = 0; i < 3; i++) 
  {
   printf("%s\n", materials[ i ]);
  }
  return 0;
}

Output:

Please remember these materials:
iron
copper
gold

Advantages of Pointers

  1. Pointers are useful for accessing memory locations.
  2. Pointers provide an efficient way for accessing the elements of an array structure.
  3. Pointers are used for dynamic memory allocation as well as deallocation.
  4. Pointers are used to form complex data structures such as linked list, graph, tree, etc.

Disadvantages of Pointers

  1. Pointers are a little complex to understand.Programmers find it very difficult to work with the pointers; therefore it is programmer's responsibility to manipulate a pointer carefully.
  2. Pointers(if used incorrectly) can lead to various errors such as segmentation faults or can access a memory location which is not required at all.
  3. If an incorrect value is provided to a pointer, it may cause memory corruption.
  4. Pointers are also responsible for memory leakage.(Find out more about Dangling Pointers to know more)
  5. Pointers are comparatively slower than that of the variables.

Try to do all the previous exercises and those solved in class with pointers as practice. Use the IDE for this.


Comments

There are no comments at the moment.