INTRODUCTION TO POINTERS IN C

 

PROGRAMMING IN C

 POINTERS IN C

(By Naresh Gupta)

 What do you mean by Memory addresses/references?

ü Computer memory consist of small cells/blocks in contiguous form.

ü Each cell have its own number starting from 0, 1, 2.. and so on.

ü This cell number called memory address or reference no.

ü Last cell number depend on memory size.

ü Each cell size is equal to 1 byte (8 bits)

ü If computer have 4 GB RAM then Total numbers of addresses are 4x1024x1024x1024 = 4294967296

ü When a variable is created in C, a memory address is assigned to the variable. 

ü The memory address is the location of where the variable is stored on the computer.

ü When we assign a value to the variable, it is stored in this memory address. 

ü Address number is always positive number (unsigned integer).

1 Cell = 1 Block = 1 address = 1 reference = 1 Byte = 8 bits

 How to access or obtained variable’s address from memory?

ü  To access it, use the (&) ‘address of operator’ (or reference operator) returns the memory address of its variable (operand). 

ü  The operator & immediately preceding a variable return the address of the variable associated with it. 

ü  Example:  

int a = 10;

float b= 100.50;

char c = ‘a’; 

printf(“address of a = %u\n”,&a);

printf(“address of b = %u\n”,&b);

printf(“address of c = %u\n”,&c); 

ü  Note: here %u format specify used for unsigned integer

 How to access or obtained value of variable at variable’s address into memory?

 ü  We use * (asterisk) operator as a prefix with variable’s address to find value at address

ü  Example:

int a = 10;

float b= 100.50;

char c = ‘a’;

printf(“The address of a = %u and value at address (a) = %d\n”, &a, *(&a));

printf(“The address of b = %u and value at address (b) = %f\n”, &a, *(&b));

printf(“The address of c = %u and value at address (c) = %c\n”, &a, *(&c));

 

What is a pointer?

 ü  A pointer is a special variable that hold (stores) the memory address of another variable which to be point. 

ü A pointer is a derived data.

ü It is built from one of the primary data types available in C.

 What are the Advantages of Pointers/Features of Pointers/Uses of Pointers? 

  • Increase the execution speed
  • Pointers save memory space in String and Array.
  • Memory is accessed efficiently with the pointers.
  • Pointers are used with data structures.
  • Pointers are used for file handling.
  • Pointers are used to allocate memory dynamically.
  • Pointer reduces the length of code.
  • We can return multiple values from function using pointer.

What are the Disadvantages /Drawbacks/Limitation of Pointers?  

  • Pointer are slower than normal variable.
  • Pointers store only address but cannot store a value
  • It requires a null pointer reference.
  • It requires one additional dereferences step  

How to Declaring Pointer Variables? 

ü  Pointer is similar to the variable declaration in C, but we use the ( * ) dereferencing operator in the pointer declaration.  

Syntax

datatype * ptr 

where

·       ptr is the name of the pointer.

·       datatype is the type of data it is pointing to. (May be int, long int, float, double, char, structure etc.)

·       ptr needs a memory address or location.  

Example

        int *p;

        char *p1;

        float *p2;

here p, p1, p2 are pointer variables, p point to int data type (p hold only integer variable’s address can’t hold char and float type variable’s address) and p1 point to char data type).  

How to Initialization of Pointer Variables?  

ü  The process of assign the address of a variable to a pointer variable is called as initialization. 

ü  Once a pointer variable has been declared we can initialize the pointer variable using assignment operator(=). 

ü  Example:

int a;           /*  Normal variable declaration */

int *p;         /*  Pointer variable declaration */

p = &a;       /*  Pointer initialization  */ 

ü  We can also combine the initialization with the declaration. That is-

int *p = &a; 

 

What is NULL Pointer?

 ü  The Null Pointer is the pointer that does not point to any location (address of memory) but NULL or 0 (zero).

ü  It represents an invalid memory location.

ü  When a NULL or 0 value is assigned to a pointer, then the pointer is considered as NULL pointer.

ü  Example:

int *p = NULL;    /* this is a NULL Pointer */

or
int *p = 0;

 

How to Accessing a Variables Through its Pointer? 

ü  Once a pointer has been assigned the variable’s address, we can access the value of variable using unary operator * (asterisk) usually known as the pointer operator/ indirection operator (dereferencing operator).

ü  Example:

int a, *p, n;    /* declaration of variables (a, n) and pointer( p) */

a = 200;        /* assign the value 200 to a */

p = &a;         /* p hold the address of a */

n =  *p;         /* *p returns the value of the variable a */

The * can be remembered as ‘value at address’ therefore, n would be 200. 

Which operators are used in Pointer in C language?

 There are two operators used for the pointers in any program:

1. * (Asterisk Symbol) called ‘Pointer operator’ or ‘value at address operator’.

     There are two uses of *

o  Declaration of pointer e.g. int *p, float *p1; here two pointer variable created as name p and  p1;

o  if we want to represents the value stored in a pointer (value at address) then used * preceded by pointer. e.g.  

int a = 100;    (declaration of normal variable)

int  *p;           (declaration of pointer)

p = &a;           (pointer initialization)  

*p = *p + 500 (here *p refer to value of a, now value of a is 600);

2. & (Ampersand Symbol): Called ‘Address of’ or ‘Referenced Operator’ and it return variable’s address value.

 Program to demonstrate pointers in C

 The program clearly shows how we can access the value of a variable using a pointer.

 /* Program Pointers in C */

#include<stdio.h>

int main()

{

         int x = 10, y = 30;

         int *ptr;

         ptr = &y;

         x = x + *ptr;

         printf (“Value of y is %d\n”, y);

         printf(“%d is stored at address = %u\n”,y, &y);

          printf(“%d is stored at address = %u\n”,*(&y),&y);

         printf(“%d is stored at address = %u\n”,*ptr, ptr);

         printf(“%d is stored at address = %u\n”,ptr, &ptr);

         printf(“%d is stored at address = %u\n”,x, &x);

         *ptr = 200;

         printf(“\nnow y is  = %d\n”, y);

         return 0;

}

 Output:

Explanation:

 

Example Program:

 /* Program : pointer to pointer */

#include<stdio.h>

int main()

{

     int num, *ptr,   **rptr;

     num = 26;

     ptr = &num;   /* address of num  */

     rptr = &ptr;   /* address of ptr  */

     printf(“num  = %d\n”, **rptr);

     return 0;

}

This code will display the value 26. Here ptr is declared as a pointer to an integer and rptr as pointer to a pointer to an integer

What is Scale Factor (Pointer Increments or Decrements)? 

ü  When we increment or decrement a pointer, its value is increased or decreased the ‘length’ of the data type (one unit) it points to.

ü  This length is called the scale factor.

ü  The unit size depends upon the data type of the pointer.

ü  For a 32 bit computer, the lengths of various data types are:

char           1 byte

int             4 bytes

float           4 bytes

double       8 bytes

long double 10 bytes.

 

Pointers and Arrays 

ü  When we declare array, the compiler allocates a base address and sufficient amount of memory to hold the all elements of the array in contiguous memory locations.

ü  Suppose we declare an array a as follows:

int a[10];          


Let the address of a (base address) is 4000 and size of int data type = 4 then

the 10 elements will be stored as follows:

ü  If we want access array using pointer we required base address and last address of array. 

How to obtained Base address of array?

ü  The name of array defined as a constant pointer to the first element, indexed 0 element. Example:

int a[10], *p; 

a  = &a[0] = 4000 (base address of array a)

p = a; or p = &a[0]; pointer p hold the base address of array a; 

How to obtained Last address of array? 

ü  The name of array defined as a constant pointer to the first element, indexed 0 element. Example:

int a[10], *p; 

Last address of array = Base Address + Total Elements-1

                                   4000+(10-1) * 4 = 4036

Write a program using pointers to read n integer values into array and compute sum and average of all values stored into array

Output:

Pointers as Function Arguments

ü  We can pass the address of a variable as an argument to a function in the normal fashion.

ü  When we pass addresses to a function, the parameters receiving the addresses should be pointers.

ü  The process of calling a function using pointers to pass the addresses of variables is known as ‘call by reference or call by address.

ü  Example

Here p represents the address of x, the value of x is changed from 20 to 50.

 

Write a C Program using pointers with function to swap two integer values

Output:

Function Returning Pointers

ü  Function can return a single value by its name or return multiple values through pointer parameters.

ü  Pointers are a data type, we can also force a function to return a pointer to the calling function. 

Example 1:

Output:

         sum = 30

Example 2:

 

Output:

What do you mean by Dynamic Memory Management?  

ü The process of allocating memory at run time is known as dynamic memory allocation.

ü Dynamic memory allocation is useful when the size required for data items is not known at compile time.

ü There are 4 library functions provided by C defined under <stdlib.h> header file for dynamic memory allocation in C programming. These are:

1.  malloc(): It stands for “memory allocation” and allocate requested size of bytes and returns a pointer to the first byte of the allocated space.

Syntax:

     ptr = (cast-type*) malloc(byte-size)

For Example:

       int *p, n = 10;

       p= (int*) malloc (n* sizeof(int))

2.  calloc(): Allocated space for an array of elements.

3.  free(): Fees previously allocated space.

4.  realloc(): Modifies the size of previously allocated space.

 

C Program read string value from keyboard and convert into reverse using pointer.

Output:

 

 

Leave a Reply