Skip to main content

Pointers and arrays

C Pointers and Arrays


Pointer is a variable that store the address of another variable
Syntax :
  <type> *ptr_name;
Two operators mostly used in pointer : * (content of) and & (address of)
Example:
Initialize an integer pointer into a data variable:
int i, *ptr;
ptr = &i;
To assign a new value to the variable pointed by the pointer:
*ptr = 5;  /* means i=5 */


#include<stdio.h>
  
int main()
{
  int arr[5] = { 1, 2, 3, 4, 5 };
  int *ptr = arr;
  
  printf("%p\n", ptr);
  return 0;
}

In this program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer that can point to whole array instead of only one element of the array. This pointer is useful when talking about multidimensional arrays.



int (*ptr)[10];
Here ptr is pointer that can point to an array of 10 integers. Since subscript have higher precedence than indirection, it is necessary to enclose the indirection operator and pointer name inside parentheses. Here the type of ptr is ‘pointer to an array of 10 integers’.
Note : The pointer that points to the 0th element of array and the pointer that points to the whole array are totally different. The following program shows this:


// C program to understand difference between 
// pointer to an integer and pointer to an
// array of integers. 
#include<stdio.h>
  
int main()
{
    // Pointer to an integer
    int *p; 
      
    // Pointer to an array of 5 integers
    int (*ptr)[5]; 
    int arr[5];
      
    // Points to 0th element of the arr.
    p = arr;
      
    // Points to the whole array arr.
    ptr = &arr; 
      
    printf("p = %p, ptr = %p\n", p, ptr);
      
    p++; 
    ptr++;
      
    printf("p = %p, ptr = %p\n", p, ptr);
      
    return 0;

p: is pointer to 0th element of the array arr, while ptr is a pointer that points to the whole array arr.
  • The base type of p is int while base type of ptr is ‘an array of 5 integers’.
  • We know that the pointer arithmetic is performed relative to the base size, so if we write ptr++, then the pointer ptr will be shifted forward by 20 bytes.
The following figure shows the pointer p and ptr. Darker arrow denotes pointer to an array.

On dereferencing a pointer expression we get a value pointed to by that pointer expression. Pointer to an array points to an array, so on dereferencing it, we should get the array, and the name of array denotes the base address. So whenever a pointer to an array is dereferenced, we get the base address of the array to which it points.




Data saved in a certain structure to be accessed as a group or individually. Some variables saved using the same name distinguish by their index.


Array characteristics:

Homogenous

  All elements have similar data type

Random Access

  Each element can be reached individually, does not have to be sequential


Source : Geeksforgeeks and PPT Binus Maya

Comments