Iterating through an array using pointers
suggest change#include <stdio.h>
#define SIZE (10)
int main(void)
{
size_t i = 0;
int *p = NULL;
int a[SIZE];
/* Setting up the values to be i*i */
for(i = 0; i < SIZE; ++i)
{
a[i] = i * i;
}
/* Reading the values using pointers */
for(p = a; p < a + SIZE; ++p)
{
printf("%d\n", *p);
}
return 0;
}
Here, in the initialization of p in the second for loop, the array a decays to a pointer to its first element, as it would in almost all places where such an array variable is used. The expression a + SIZE points one past the last element, so the comparison p < a + SIZE is defined and *p is not evaluated at that address.
Then, the ++p performs pointer arithmetic on the pointer p and walks one by one through the elements of the array, and refers to them by dereferencing them with *p.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents