English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn about the relationship between array and pointer in C programming. You will also learn to access array elements using pointers.
Before understanding the relationship between array and pointer, make sure to check the following two subjects:
An array is an ordered data block. Let's write a program to print the address of array elements.
#include <stdio.h> int main() { int x[4]; int i; for(i = 0; i < 4; ++i) { printf("&x[%d] = %p\n", i, &x[i]); } printf("Address of x array: %p", x); return 0; }
Output result
&x[0] = 1450734448 &x[1] = 1450734452 &x[2] = 1450734456 &x[3] = 1450734460 the address of x array: 1450734448
the difference between two consecutive elements of array x is4bytes. This is because the size of int is4bytes (in our compiler).
Please note that the address &x[0] is the same as x. This is because the variable name x points to the first element of the array.
From the above example, it can be clearly seen that &x[0] is equivalent to x. And, x[0] is equivalent to*x.
Similarly,
&x[1] is equivalent to x+1 and x[1] is equivalent to*(x+1).
&x[2] is equivalent to x+2 and x[2] is equivalent to*(x+2).
...
basically &x[i] is equivalent to x+i and x[i] are equivalent to*(x+i).
#include <stdio.h> int main() { int i, x[6], sum = 0; printf("Input6numbers: "); for(i = 0; i < 6; ++i) { // is equivalent to scanf("%d", &x[i]); scanf("%d", x+i); // is equivalent to sum += x[i] sum += *(x+i); } printf("Sum = %d", sum); return 0; }
The output when running the program is:
Input6numbers: 2 3 4 4 12 4 Sum = 29
Here, we declare an array containing6an array of elements x. To access the elements of the array, we use pointers.
In most cases, the array name decays to a pointer. In short, the array name is converted to a pointer. This is why you can use pointers to access array elements. However, you should remember thatPointer and array are not the same.
In some cases, the array name does not decay to a pointer.
#include <stdio.h> int main() { int x[5] = {1, 2, 3, 4, 5}; int* ptr; //ptr was allocated the address of the third element ptr = &x[2]; printf("*ptr = %d \n", *ptr); // 3 printf("*(ptr+1) = %d \n", *(ptr+1)); // 4 printf("*(ptr-1) = %d", *(ptr-1)); // 2 return 0; }
The output when running the program is:
*ptr = 3 *(ptr+1) = 4 *(ptr-1) = 2
In this example, the address of the third element &x [2] is assigned to the ptr pointer. Therefore, when we print* ptr is displayed3.
and, output*(ptr+1) gets the fourth element. Similarly, output*(tr-1Thus, the second element is obtained.