Arrays: Indexes versus Pointers


The Programs: Here are two C programs side-by-side, with normal arrays on the left and C "dynamic" arrays on the right. Selected major differences between the programs are highlighted in red.

Ordinary C arrays Dynamic C arrays
#include <stdio.h>

#define SIZE 4
void init(int a[], int size);
void print(int a[], int size);

int main() {
int a[SIZE];
init(a, SIZE);
print(a, SIZE);

}

void init(int a[], int size) {
int i;
for (i = 0; i < size; i++)
a[i] = i*i + 1;
}

void print(int a[], int size) {
int i;
for (i = 0; i < size; i++) {
printf("a[%i]=%i", i, a[i]);
printf( i < size-1 ? ", " : " ");
}
}
#include <stdio.h>
#include <stdlib.h> /* for malloc & free */
#define SIZE 4
void init(int *p, int size);
void print(int *p, int size);

int main() {
int *p = (int *)malloc(sizeof(int) * SIZE);
init(p, SIZE);
print(p, SIZE);
free(p); } void init(int *p, int size) {
int i;
for (i = 0; i < size; i++)
*(p+i) = i*i + 1;
}

void print(int *p, int size) {
int i;
for (i = 0; i < size; i++) {
printf("*(p+%i)=%i", i, *(p+i));
printf( i < size-1 ? ", " : " ");
}
}
Output Output
a[0]=1, a[1]=2, a[2]=5, a[3]=10
*(p+0)=1, *(p+1)=2, *(p+2)=5, *(p+3)=10

The two notations, index and pointer, are mostly interchangable, even in the same program. To illustrate this, I took the two programs above and interchanged the function definitions. Notice that I kept the prototypes the same, so they don't seem to match the function definition any more. Everything works perfectly, and even lint is happy with this code.

Functions Interchanged, Prototypes Not
#include <stdio.h>

#define SIZE 4
void init(int a[], int size);
void print(int a[], int size);

int main() {
int a[SIZE];
init(a, SIZE);
print(a, SIZE);

}

void init(int *p, int size) {
int i;
for (i = 0; i < size; i++)
*(p+i) = i*i + 1;
}

void print(int *p, int size) {
int i;
for (i = 0; i < size; i++) {
printf("*(p+%i)=%i", i, *(p+i));
printf( i < size-1 ? ", " : " ");
}
}
#include <stdio.h>
#include <stdlib.h> /* for malloc & free */
#define SIZE 4
void init(int *p, int size);
void print(int *p, int size);

int main() {
int *p = (int *)malloc(sizeof(int) * SIZE);
init(p, SIZE);
print(p, SIZE);
free(p);
}

void init(int a[], int size) {
int i;
for (i = 0; i < size; i++)
a[i] = i*i + 1;
}

void print(int a[], int size) {
int i;
for (i = 0; i < size; i++) {
printf("a[%i]=%i", i, a[i]);
printf( i < size-1 ? ", " : " ");
}
}

Output Output
*(p+0)=1, *(p+1)=2, *(p+2)=5, *(p+3)=10
a[0]=1, a[1]=2, a[2]=5, a[3]=10


Created By Dr. Neal Wager : The University of Texas at San Antonio