Skip to main content

Posts

Showing posts with the label pointer

Static and dynamic memory allocation

Static memory allocation    It refers to the allocation of memory during compilation of program. Memory bindings are not established and destroyed during the execution Variables remain permanently   allocated. Faster execution than dynamic. More memory space required. Data is stored in data segment of memory.  

Memory leaks and dangling pointers

If the allocated memory is not released or de-allocated, it causes a memory leak. /* Function with memory leak because programmer forgot to release dynamically allocated memory */  #include<stdlib.h>  void f()  { int *ptr =(int*) malloc(10*sizeof(int));  /* Do some work */  return; /* returns without freeing ptr*/  }  /* Function without memory leak because memory freed by programmer when no longer needed*/  #include<stdlib.h>  void f()  { int *ptr =(int*) malloc(10*sizeof(int));  /* Do some work */  free (ptr):  return;  } A dangling pointer points to a memory location that has already been freed. If we try to access the memory location using the pointer it causes a segmentation fault.  /* Function without memory leak */  #include<stdlib.h>  void f()  {  int *ptr =(int*) malloc (sizeof(int))  *ptr = 10; //valid  *free (ptr):  **ptr = 20; // invalid becaus...

Memory allocation for 2D array

Memory allocation for 2-D array (matrix of ‘r’ rows and ‘c’ columns)  Here, we use ‘r’ number of pointers, one pointer for each row. Hence, we can use an array of pointers. Memory is allocated row-wise, i.e. allocate memory for each row (of c elements) separately. Each address in the array points to a row of ‘c’ elements as illustrated below.  row[0] contains the address of 0th element. Any element of this matrix can be accessed by specifying the row address and the offset.   The address of the (i,j)th element, will be row[i]+j  The value of the i, jth element will be *(row[i]+j)

Dynamic memory allocation

The ‘C’ programming language supports Dynamic memory allocation in which the programmer can allocate and de-allocate memory whenever required. Dynamic memory allocation means memory allocation and deallocation at runtime, as and when required.  Allocating a block of memory using malloc() function  The malloc() function allocates the specified number of bytes and returns the address of the first byte of the block. It returns NULL if allocation is unsuccessful or if num is 0. Explicit type casting is required because by  default, malloc returns a void pointer.  Syntax: pointer =(datatype*)malloc(number_of_bytes); Example:  int *ptr; /* pointer to the block*/  ptr=(int *)malloc(n *sizeof(int)); Allocating a block of memory using calloc() function  It allocates a group of objects and initializes the bytes to 0.  Syntax: void *calloc(int num, int size);  Here num is the number of objects to allocate and size is the size (in bytes) of each object...

Pointer const and Constant Pointer

A constant pointer is a pointer that cannot change the address which it stores.   Syntax: datatype *const pointer_name;  Example:  int a=10,b=20;  int *const ptr;  ptr=&a;  ptr=&b; //here the address in ptr cannot be changed so not allowed . Pointer to constant  Address in the pointer can be changed but the value of the data element which the pointer points cannot be changed.  Syntax: const datatype * pointer_name;  Example:  int a=10,b=20;  const int *ptr=&a;  *ptr=100; //here the value which ptr points to cannot changed so not allowed ptr=&b; //allowed Pointers and Const  The previous two can be combined to form a constant pointer to constant  Syntax: const datatype *const pointer_name; Example:  const int * const ptr;  int a=10,b=20;  const int * const ptr=&a;  *ptr=100; //not allowed  ptr=&b;//not allowed  Here the value which ptr points to cannot be changed an...

Some pointer declaration and their meaning

int * p; : p is a pointer to an integer. int p[10]; : p is an array of 10 integers. int *p[10]; : p is an array of 10 pointers to integers. int (*p)(int); : p is function pointer which takes an integer as argument and returns an int. int p (char a); : p is a function accepting a character and returning an integer. int p(char *a); : p is a function accepting a character pointer and returning an integer. int *p(char a); : p is a function accepting a character and returning a pointer to an integer. int *p(char *a); : p is a function accepting a character pointer and returning an integer pointer. int **p; : p is a pointer to pointer. int p(char (*a)[10]); : p is a function that accepts a pointer to an array of character and returns an integer. int (*p)[10]; : p is a pointer to an array of 10 integers.

Functions and pointers

Pointers are often used with functions in two ways.  Passing address to a function  If we want to modify the passed value of variable in function we must pass the address of variables to the function.  Example:  void display(int *ptr);  int string_length(char *str);  void swap(int *p1,int *p2);  C program using pointer as function argument:   #include<stdio.h>  change(int *ptr1,int *ptr2);  main()  {  int a=10,b=20;  printf("\nBefore Change a=%d b=%d",a,b);  change(&a,&b); //passing address to function as argument  14) printf("\nAfter Change a=%d b=%d\n",a,b);   }   change(int *ptr1,int *ptr2)//ptr1 points to a and ptr2 points to b   { *ptr1=200;   *ptr2=300;  }   Before Change a=10 b=20   After Change a=200 b=300 Functions and pointers    C Program passing an array to a function :   #include<stdio.h...

Initializing pointer to pointer

An array of pointers and a pointer can be initialized during declaration as illustrated by following examples.  int a[]={0,1,2,3,4};  int *p[]={a,a+1,a+2,a+3,a+4};  int **ptr=p;  Here ‘a’ is an array of integers, ‘p’ is an array of pointers which stores addresses of array elements and ‘ptr’ is a pointer to pointer which stores base address of array ‘p’. Also Read Static and Dynamic Memory Allocation Memory Leak and Dangling Pointer Memory Allocation for 2D Array Dynamic Memory Allocation Pointer Constant and Constant Pointer Pointer Declarations and their Meanings Functions and Pointers Pointer to Pointer Multiple Indirection Relationship between Arrays and Pointers Pointer to Array Pointer Arithmetic Types of Pointers Illustrate Basic Pointer Use Using Pointer Intializing Pointer Declaring Pointer Application of Pointers Value Model VS Reference Model What is Pointer

Pointer to Pointer (Multiple Indirection)

Pointer which holds address of another pointer is called as pointer to pointer. It is also called as double pointer.  Syntax: int **ptr_to_ptr;  Example:  int i=10;  int *ptr; //pointer to an integer  int **ptr_to_ptr: //pointer to a pointer  ptr=&i;  ptr_to_ptr = &ptr;  C Program to illustrate pointer to pointer.  #include<stdio.h>   void main()  {  int i=10,*p1,**p2;  p1= &i;  p2=&p1;  printf(“\n the value of i is %d %d %d ”,i,*p1,**p2);  printf(“\n the address of i is %u %u %u”,&i,p1,*p2);  }  In above program p1 is pointer and p2 is a pointer to pointer.  Pointer to pointer is often used in handling of strings, multidimensional arrays.  Also Read Static and Dynamic Memory Allocation Memory Leak and Dangling Pointer Memory Allocation for 2D Array Dynamic Memory Allocation Pointer Constant and Constant Pointer Pointer Declarations and the...

Relationship between Arrays and Pointers

Array of pointers C program having an array of three pointers which are assigned the addresses of three integer variables.   #include<stdio.h>  main()  { int arr[3]={1,2,3};  int *ptr[3],i;  for(i=0;i<3;i++)  { ptr[i]=arr+i; // assigning addresses of elements to array of pointers  }  for(i=0;i<3;i++)  { printf(“\n address = %u value=%d”, ptr[i], *ptr[i]); }  }  Here output will be address of elements and its value.  Address = 3219018020 value=1  Address = 3219018024 value=2  Address = 3219018028 value=3 Also Read Static and Dynamic Memory Allocation Memory Leak and Dangling Pointer Memory Allocation for 2D Array Dynamic Memory Allocation Pointer Constant and Constant Pointer Pointer Declarations and their Meanings Functions and Pointers Initializing Pointer to Pointer Pointer to Pointer Multiple Indirection Pointer to Array Pointer Arithmetic Types of Pointers Illustrat...

Pointer to array

In following C program the array elements are accessed using pointer. Pointer stores base address of an array. Hence in this program ptr is a pointer to array x.  #include< stdio.h>  main()  {  int x[ ]={10,20,30,40,50};  int *ptr,i;  ptr=x; //ptr store base address of array  for(i=0;i<5;i++,ptr++)  {  printf(“\n address = %u”, &x[i]);  printf(“elements=%d %d %d %d”, x[i],*(x+i), i[x], *ptr);  }  }  In ‘C’ language all arrays are implemented as pointers. Hence x[i] => *(x+i) => *(i+x) => i[x] all are equivalent statement. Also Read Static and Dynamic Memory Allocation Memory Leak and Dangling Pointer Memory Allocation for 2D Array Dynamic Memory Allocation Pointer Constant and Constant Pointer Pointer Declarations and their Meanings Functions and Pointers Initializing Pointer to Pointer Pointer to Pointer Multiple Indirection Relationship between Array and Pointer Pointer Ar...

Pointer Arithmetic

Increment and Decrement When we increment an integer pointer by1, it increments by sizeof(int).  Example:  int i=20;  int *ptr=&i;  i ptr ptr++ ptr   20 1000 1002  1000 2058 or ++ptr 2058  If a pointer is decremented by 1, it is decremented by the size of the data item it points to.  When a pointer is incremented by 1 the new value will be (current address in pointer) + sizeof(data_type)  Pointer Arithmetic Continued …  Addition and Subtraction ‘C’ allows integers to be added to or subtracted from pointers. When an integer value i is added to a pointer, the new address in the pointer will be  (current address in pointer) + i* sizeof(data type)  Example: int *ptr1, n;  ptr1=&n;  ptr1=ptr1+3;  This code will increment the contents of ptr1 by 3*sizeof(int). If the address in the pointer is 1000, the new address will be 1006. The same concept applies for decrementing a pointer. Pointer Arithmetic Cont...

Types of pointers

Types of pointers NULL pointer if a pointer does not point to any variable, it can be initialized to NULL to indicate that it does not hold any valid address.  Example: int *ptr=NULL;  Dangling pointer  A pointer which holds the address of a variable which no longer exists, is a dangling pointer. Example:  void main()  { int *ptr;  { int num=10;  ptr=&num;  } //num is destroyed  //ptr is still holds address of num so it is dangling pointer.  } Generic/void pointer A pointer which points to ‘void’ data type is called a generic pointer. In ‘C’, void represents the absence of type, so void pointers are pointers that point to a value that has no type. This allows void pointers to point to any data type.  Example:  void *ptr;  (int *)ptr=&n;  Uninitialized/wild pointer A pointer which has not been assigned any address till it is first used in a program is called an uninitialized or wild pointer. It contains some ga...

Illustrate basic pointer use

Illustrate basic pointer use  #include<stdio.h>  void main()  {  /*declarations */  int n=20,*ptr_n;  ptr_n=&n;  /* Displaying value*/  printf(“\n Direct access, value=%d”, n);  printf(“\n Indirect access, value=%d”, *ptr_n);  /*Displaying address */  printf(“\n\n Direct access, address=%u”, &n);  printf(“\n Indirect access, address=%u”, ptr_n);  /* Modifying value */  n=30;  /*Direct modification */    printf(“n\n Direct modification, value=%d %d”, n,*ptr_n); *ptr_n=50;  /*Indirect modification */  printf(“\n Indirect modification, value=%d %d”, n,*ptr_n); } Also Read Static and Dynamic Memory Allocation Memory Leak and Dangling Pointer Memory Allocation for 2D Array Dynamic Memory Allocation Pointer Constant and Constant Pointer Pointer Declarations and their Meanings Functions and Pointers Initializing Pointer to Pointer Pointer to Pointer Multiple Indir...

Using a pointer

Using a pointer  Following example shows how a pointer can be used to access the value in a variable.  int n=20,x; n x 20 garbage  1002 2000  int *ptr_n; /*uninitialized pointer*/ ptr_n garbage  1006  ptr_n=&n; /* store address of n in ptr_n */ ptr_n  1002  1006  *ptr _n = 30; /*modify value */ n  30 1002  Here we have accessed the contents of variable n using the pointer ptr_n. This can be done using the *operator.  *(ptr_n) => value at(ptr_n) => value at 1002 => 30   Also Read Static and Dynamic Memory Allocation Memory Leak and Dangling Pointer Memory Allocation for 2D Array Dynamic Memory Allocation Pointer Constant and Constant Pointer Pointer Declarations and their Meanings Functions and Pointers Initializing Pointer to Pointer Pointer to Pointer Multiple Indirection Relationship between Array and Pointer Pointer to Array Pointer Arithmetic Types of Pointer Illustr...

Initializing Pointers

Initializing Pointers  Assigning an address to a pointer is called pointer initialization. Address of a variable must be stored in the pointer before it is used. This is done using the address-of (&) operator.  Syntax  pointer=&variable;  Example:  ptr=&n; //assign address of n to ptr   int a[10];  ptr=a; //assign base address of array a to ptr char str[10]=“ABCD”;   char *ptr =str; //the pointer ptr points to a string ABCD Also Read Static and Dynamic Memory Allocation Memory Leak and Dangling Pointer Memory Allocation for 2D Array Dynamic Memory Allocation Pointer Constant and Constant Pointer Pointer Declarations and their Meanings Functions and Pointers Initializing Pointer to Pointer Pointer to Pointer Multiple Indirection Relationship between Array and Pointer Pointer to Array Pointer Arithmetic Types of Pointer Illustrate Basic Pointer Use Using Pointer Declaring Pointer Applicat...

Declaring pointers

Declaring Pointers  Pointer is a variable it has to be declared before it can be used.  Syntax : data_type* pointer_name;  data_type is any ‘C’ data type and it indicates the type of the variable that the pointer points to.   (*) is indirection operator  pointer_name is a valid C identifier  Examples:  char *p_ch1,*p_ch2 ; /*p_ch1 and *p_ch2 are pointer to type char */  int *ptr_num; /*ptr_num is a pointer to an integer*/ Also Read Static and Dynamic Memory Allocation Memory Leak and Dangling Pointer Memory Allocation for 2D Array Dynamic Memory Allocation Pointer Constant and Constant Pointer Pointer Declarations and their Meanings Functions and Pointers Initializing Pointer to Pointer Pointer to Pointer Multiple Indirection Relationship between Array and Pointer Pointer to Array Pointer Arithmetic Types of Pointer Illustrate Basic Pointer Use Using Pointer Intializing Pointer Application of Pointers ...

Application of pointers

Pointers are used to pass parameters by reference, i.e. the argument can be modified.  All arrays are pointers in ‘C’ language. Pointers are used for passing arrays and strings to functions.  Pointers are used in complex data structures like linked lists, trees, graphs, etc.  Pointerss are used for dynamic memory allocation.  All file handling operations in ‘C’ are performed using pointers. Also Read Static and Dynamic Memory Allocation Memory Leak and Dangling Pointer Memory Allocation for 2D Array Dynamic Memory Allocation Pointer Constant and Constant Pointer Pointer Declarations and their Meanings Functions and Pointers Initializing Pointer to Pointer Pointer to Pointer Multiple Indirection Relationship between Array and Pointer Pointer to Array Pointer Arithmetic Types of Pointer Illustrate Basic Pointer Use Using Pointer Intializing Pointer Declaring Pointer Value Model VS Reference Model What is Pointer

Value Model vs Reference Model

Value Model vs Reference Model In programming languages, two different models are used for variables.  These are:  Value Model  A variable contains a value. The name of the variable gives its value.  Reference Model A variable contains (say y) refers to another variable (say x) with a value. The variable ‘y’ is used to access the value of ‘x’ indirectly.  The ‘C’ language is based on value model. However, by using pointers, we can implement the reference model. The pointer is used to access the value of a variable indirectly. Also Read Static and Dynamic Memory Allocation Memory Leak and Dangling Pointer Memory Allocation for 2D Array Dynamic Memory Allocation Pointer Constant and Constant Pointer Pointer Declarations and their Meanings Functions and Pointers Initializing Pointer to Pointer Pointer to Pointer Multiple Indirection Relationship between Array and Pointer Pointer to Array Pointer Arithmetic Types of Pointer Illustrat...

What is the pointer

Pointer A pointer is a variable that stores the memory address of another variable.  In above example ‘ptr’ is a pointer variable because it stores the address of another variable ‘n’. Hence it is called a pointer to n. Since a pointer is a variable, it will also occupy some memory location.  Value of variable ‘n’ can be accessed in two ways:  Using the name of the variable i.e. ‘n’  Using pointer Reference and De-reference Referencing means taking the address of an existing variable (using &) to set a pointer variable.  The operation of accessing variable using the pointer is called ‘dereference’. For example, accessing variable ‘n’ using ‘ptr’ is called dereference. De-referencing is the operation to access or manipulate data contained in the memory location pointed to by a pointer. The ‘&’ operator is used for reference. It is also called the ‘address-of ‘operator. The ‘*’ operator is used for dereference. It is also called the ‘value-at’ operator....