Originally published by Robert Beisert at fortcollinsprogram.robert-beisert.com

Linux + C – Arrays as Pointers

We’ve dealt with arrays a little bit in the past. Did you know that that whole time, we were dealing with pointers?

Array as a Pointer

When we declare an array, we are really doing the following things:

  • Allocating a section of memory large enough to contain N objects of the chosen data type
  • Creating a pointer to the start of that memory section
  • Preserving (by data type) the size of each object in the array

In fact, when we give the index of an array value, we are telling the program to go to the memory location, then travel to the location of the object we want. For example, if we have an array of 25 characters, and each character is 8 bits long, then the index

array[15]

is telling the program to start at the pointer called array, travel 8*15=120 bits past that point, then read the following 8 bits.

arr_point.c

Need more proof? We’ll demonstrate it by pointing to the array, and comparing that to the location of the objects in that array. We’ll also show how we can put a string into an array, and pull it back out (exactly like a char *, with a maximum size limit).

Pay attention to how your computer indexes its data locations. Generally, we count by byte, so a char takes up one (1) addressable location. At the same time, an int will generally take up four (4) addressable locations.

#include <stdio.h>

int main(int argc, char *argv[])
{
int i;
char *pointer;
char arr[25] = "Hello, world!/n";

for(i = 0; i <25; i++)
{
pointer = &arr[i];
printf("%pt%pt%c/n";, pointer, &arr[i], arr[i]);
}

return 0;
}