C Programming Pointers and Arrays

C Programming Pointers and Arrays

C Programming Pointers and Arrays
In this chapter you will learn about the relationship between array and pointer and you will learn how to use them properly in your program.

Table of Contents

C Programming Pointers and Arrays

Array and pointer are almost same in C programming . But the important difference between them is that the value of the pointer can have different addresses whereas the address of the array is fixed.

The following examples illustrate the difference between them:

				
					#include <stdio.h>
int main()
{
   char charArr[4];
   int i;

   for(i = 0; i < 4; ++i)
   {
      printf("Address of charArr[%d] = %u\n", i, &charArr[i]);
   }

   return 0;
}

				
			

output

				
					Address of charArr[0] = 28ff44
Address of charArr[1] = 28ff45
Address of charArr[2] = 28ff46
Address of charArr[3] = 28ff47
				
			

Note: You can get different address of array.

If you look at the result of the above example, you will see that the difference between the two elements of the charArr array is equal. That is, their difference is 1 byte.

But since a pointer points to the location of another variable, it can store any address.

Relationship between Array and Pointer in C Programming

Consider an array like the following:

				
					int arr[4];

				
			

In C  programming, the array name always refers to the address of the first element of the array.

In the above program   both arr and &arr[0]   point to the address of the first element.

				
					&arr[0] is usually equal to arr

				
			

Since both have the same address, the values ​​of arr and &arr[0] are also the same.

				
					arr[0] is usually equal to *arr(pointer address value).

				
			

Similarly,

				
					&arr[1] is usually equal to (arr + 1) and arr[1] is usually equal to *(arr + 1).
&arr[2] is usually equal to (arr + 2) and arr[2] is usually equal to *(arr + 2).
&arr[3] is usually equal to (arr + 1) and arr[3] is usually equal to *(arr + 3).
.
.
&arr[i] is usually equal to (arr + i) and arr[i] is usually equal to *(arr +
				
			

In C programming you can declare an array and change the data of this array using pointers.

Example: Program to find sum of 5 integers using Array and Pointer.

				
					#include <stdio.h>
int main()
{
 int i, classes[5], sum = 0;
 printf("Enter 5 numbers:\n");
 for(i = 0; i < 5; ++i)
 {
 // (classes + i) is usually equal to &classes[i].
 scanf("%d",(classes + i));

 // *(classes + i) is usually equal to classes[i].
 sum += *(classes + i);
 }
 printf("Sum = %d", sum);
 return 0;
}
				
			

output

				
					Enter 5 numbers:
5
4
10
5
7
Sum = 31
				
			

Leave a Comment

Your email address will not be published. Required fields are marked *