C Language | Pointers | Arrays and Pointers

This article explains how pointers refer to arrays and access individual elements.

Dereferencing Arrays

In most expressions, an array name is converted to the address of its first element.

int *iPo = &iArray[0];
int *iPo = iArray;

Both declarations store the same address. The array itself is not an assignable pointer variable.

Code 1

#include <stdio.h>

int main() {
 char chStr[] = "Kitty on your lap";
 printf("&chStr[0] = %p, chStr = %p\n" , (void *)&chStr[0] , (void *)chStr);
 return 0;
}

Array indexing is equivalent to pointer arithmetic and dereferencing.

iArray[index]
*(iArray + index)

Likewise, &iArray[index] is equivalent to iArray + index.

Code 2

#include <stdio.h>

int main() {
 int iArray[] = { 2 , 4 , 8 };
 printf("dereference = %d, %d, %d\n" , *iArray , *(iArray + 1) , *(iArray + 2));
 printf("index = %d, %d, %d\n" , iArray[0] , iArray[1] , iArray[2]);
 return 0;
}

Parentheses matter. *iPo++ increments the pointer after dereferencing it, while (*iPo)++ increments the referenced value.

Multidimensional Arrays

Multidimensional arrays are stored contiguously, but each dimension remains part of the type. For example, an int [2][2] contains four adjacent integers.

int iArray[2][2] = { { 1 , 2 } , { 3 , 4 } };

The expression iArray[0] refers to the first row, and iArray[0][0] refers to its first integer. Preserve dimension information when possible instead of flattening the array with a cast.

Passing Arrays to Functions

Functions commonly receive arrays through pointers to avoid copying large blocks of data.

Code 3

#include <stdio.h>

void stringToLower(char *text) {
 int index;
 for(index = 0 ; text[index] ; index++) {
   if (text[index] >= 'A' && text[index] <= 'Z')
     text[index] += 'a' - 'A';
 }
}

int main() {
 char text[] = "KITTY on YOUR lap";
 stringToLower(text);
 printf("%s\n" , text);
 return 0;
}

For a function parameter, char *text and char text[] are adjusted to the same pointer type. The pointer notation makes the behavior explicit.