Skip to main content

Pointers and arrays in c

POINTERS AND ARRAYS:
What is an array?
An array is a data structure consisting of elements of similar data type.  The elements of an array are stored in consecutive memory locations.

How to declare an array?
Below is the template for array declaration.
datatype  name[number of elements];
          int   num[10];
Here, num is array of 10 integers.

How to access array elements?
Array indices are used to access array elements.  And the array index starts from zero.
      int arr[5] = {1, 2, 3, 4, 5};
arr[0] gives us the element at the 0th index in the array arr.  Let us try to read the array elements one by one.
arr[0] is 1 
arr[1] is 2 
arr[2] is 3 
arr[3] is 4 
arr[4] is 5 

How to access array elements using pointers?
To access array elements, assign the base address of array to the pointer.
     int *ptr;
     int arr[5] = {10, 20, 30, 40, 50};
     ptr = &arr[0];
Now, the pointer refers to the address of first element in the array arr.

*(ptr + 0) refers to the content of arr[0]

Then, *(ptr + i) refers to the content of arr[i].  So, the element at the array index i can be access by dereferencing the pointer (ptr + i).
ie. *(ptr + i) <=> arr[i]

How to write values in an array using pointers?
To write values in an array using pointers, assign the base address of array to pointer.  Then, assing value to the object refereced by pointer as shown below.
*(ptr + 0) = 100;
*(ptr + 1) = 200;
*(ptr + 2) = 300;
*(ptr + 3) = 400;
*(ptr + 4) = 500;

So, we have updated the array elements using pointers and the element in the array arr are as follows.
     arr[5] = {100, 200, 300, 400, 500};

Below program explains how to read values from an array and write values to array using pointers.


  #include <stdio.h>
  int main() {
        int i, arr[5], input;
        printf("Enter array inputs:\n");
        for (i = 0; i < 5; i++) {
                printf("arr[%d]: ", i);
                scanf("%d", &input);
                /* assigning values to array elements using pointers */
                *(arr + i) = input;
        }

        printf("\nReading array elements using pointer:\n");
        for (i = 0; i < 5; i++) {
                printf("arr[%d]: %d\n", i, *(arr + i));
        }
        return 0;
  }




  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter array inputs:
  arr[0]: 10
  arr[1]: 20
  arr[2]: 30
  arr[3]: 40
  arr[4]: 50

  Reading array elements using pointer:
  arr[0]: 10
  arr[1]: 20
  arr[2]: 30
  arr[3]: 40
  arr[4]: 50



How to access two dimensional array using pointers?
Consider the following two dimensional array.
int num[2][2] = {{1, 2}, {3, 4}};

Pointer notation           Subscript notation            Value
**num                             num[0][0]                          1
*(*num + 1)                     num[0][1]                           2
*(*(num + 1))                   num[1][0]                          3
*(*(num + 1) + 1)              num[1][1]                          4

Using the above pointer notation, we can access two dimensional array using pointers.

How to write values into a two dimensional array using pointers?
**num                   = 10;
*(*num + 1)           = 20;
*(*(num + 1))         = 30;
*(*(num + 1) + 1)   = 40;

So, we have updated the values of a two dimensional array.  And the elements in the array num are as follows.
     num[2][2] = {{10, 20}, {30, 40}};

Below program explains how to read values from a multidimensional array and write values to a multidimensional array.


  #include <stdio.h>
  int main() {
        int i, j, num[2][2] = {{1, 2}, {3, 4}};
        printf("Reading two dimensional array using pointer:\n");
        for (i = 0; i < 2; i++) {
                for (j = 0; j < 2; j++) {
                        printf("num[%d][%d]: %d\n", i, j, *(*(num + i) + j));
                }
        }

        /* writing values to a 2d array */
        for (i = 0; i < 2; i++) {
                for (j = 0; j < 2; j++) {
                        *(*(num + i) + j) = num[i][j] + 100;
                }
        }

        printf("\nReading the updated values in 2d array using pointer:\n");
        for (i = 0; i < 2; i++) {
                for (j = 0; j < 2; j++) {
                        printf("num[%d][%d]: %d\n", i, j, *(*(num + i) + j));
                }
        }

        return 0;
  }




  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Reading two dimensional array using pointer:
  num[0][0]: 1
  num[0][1]: 2
  num[1][0]: 3
  num[1][1]: 4

  Reading the updated values in 2d array using pointer:
  num[0][0]: 101
  num[0][1]: 102
  num[1][0]: 103
  num[1][1]: 104


Comments

Popular posts from this blog

restorecrtmode example in c

Header file:     graphics.h Synopsis:        void restorecrtmode();       Description:       restorecrtmode() restores screen mode to text mode. restorecrtmode function in c graphics   #include <graphics.h>   #include <stdlib.h>   #include <stdio.h>   #include <conio.h>   int main(void) {         /* request auto detection */         int gd = DETECT, gmode, err;         int midx, midy;         /* initialize graphics and local variables */         initgraph(&gd, &gmode, "C:/TURBOC3/BGI");         /* read result of initialization */         err = graphresult();         if (err != grOk) {                 /* an error occurred */               ...

How to install JDK and setting environment variables for java

In this tutorial, we are going to see the following. How to install JDK How to run java program without setting java path How to set temporary java path in windows How to set permanent java path in windows How to install JDK? Check whether JDK is installed on your PC.  If it is not installed, please go to the below link and download JDK under Java SE(Java Standard Edition) in oracle website . Install the downloaded JDK in your PC. Once JDK is installed, you can run your java program using any method shown below. Having your java source code under jdk/bin, compile the source code and run the program from same directory Setting temporary path for java, compiling the source code and running the program from any location using command prompt Updating the java path in system or user variable(in system properties), compiling the source code and running the program anywhere using command prompt Let us see how to run java program without setting environmental variables.  Once java is ...

Save image in Microsoft Paint without white background

Here, we are going to see how to save image in mspaint without white background 1. Create your own drawing or painting 2. Crop the needed portion of your drawing or painting or image. Here, I am going to crop the porting inside the red box. Now, we have cropped the portion that needs to be saved as an image. 5. Clear the screen and paste the image which we cropped earlier. 6. Decrease the screen size by 50% 7. Now, adjust your screen to fit to your image size. 8. Save the image to desired file format(jpeg, png, bmp etc) 9. Go to the saved location and open the file.  Below is the output image of mine Hope you liked this article!!  For any suggestions, please comment below.