Understanding Pointers to Arrays in C
This section explores how arrays in C are treated as pointers, specifically focusing on how the array name serves as a constant pointer to its first element. Gain insights into pointer arithmetic, array manipulation, and effective memory management in your C programs.
Pointer to an Array in C
An array name in C is treated as a constant pointer to the first element of the array. For example, in the declaration:
Code Example
int balance[5];
Here, balance
acts as a pointer to &balance[0]
, which is the address of the first element of the array.
Example
In this example, we have a pointer ptr
that points to the address of the first element of an integer array called balance
:
Code Example
#include <stdio.h>
int main() {
int *ptr;
int balance[5] = {1, 2, 3, 4, 5};
ptr = balance;
printf("Pointer 'ptr' points to the address: %d", ptr);
printf("\nAddress of the first element: %d", balance);
printf("\nAddress of the first element: %d", &balance[0]);
return 0;
}
Output
Pointer 'ptr' points to the address: 647772240
Address of the first element: 647772240
Address of the first element: 647772240
In all three cases, you will get the same output. If you fetch the value stored at the address that ptr
points to (i.e., *ptr
), it will return 1
.
Array Names as Constant Pointers
It is valid to use array names as constant pointers, and vice versa. For instance, *(balance + 4)
is a legitimate way to access the data at balance[4]
.
Once you store the address of the first element in ptr
, you can access the array elements using *ptr
, *(ptr + 1)
, *(ptr + 2)
, and so on.
Example
The following example demonstrates the concepts discussed above:
Code Example
#include <stdio.h>
int main() {
/* an array with 5 elements */
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *ptr;
int i;
ptr = balance;
/* output each array element's value */
printf("Array values using pointer: \n");
for(i = 0; i < 5; i++) {
printf("*(ptr + %d): %f\n", i, *(ptr + i));
}
printf("\nArray values using balance as address:\n");
for(i = 0; i < 5; i++) {
printf("*(balance + %d): %f\n", i, *(balance + i));
}
return 0;
}
Output
Array values using pointer:
*(ptr + 0): 1000.000000
*(ptr + 1): 2.000000
*(ptr + 2): 3.400000
*(ptr + 3): 17.000000
*(ptr + 4): 50.000000
Array values using balance as address:
*(balance + 0): 1000.000000
*(balance + 1): 2.000000
*(balance + 2): 3.400000
*(balance + 3): 17.000000
*(balance + 4): 50.000000
In this example, ptr
is a pointer that can store the address of a variable of type double
. Once the address is stored in ptr
, *ptr
will give you the value available at that address.