link_between_pointers_and_array

“The name of an array can be used as a pointer to the first element in the array”

pointer arithmetic

adding an integer to a pointer

int *p;
int j = 5;

int a[] = {0,1,2,3,4,5,6,7}

p = &a[2];
/* p + 3 will point to a[5] */

p += 4;
/* p points to a[6] */
printf("*p is %d", *p); /* should be a[6] == 6 */

subtracting an integer to a pointer

This is similar to adding an integer.

int *p;
int j = 5;

int a[] = {/* populate */}

p = &a[12];
/* p - 3 will point to a[9] */

p -= 4;
/* p points to a[8] */

difference between 2 pointers

p = &a[5];
q = &a[7];

i = q - p; /* evaluates to 2  */
i = p - q; /* evaluates to -2 */

array processing with pointers

#define N 10

int a[N], sum, *p;

sum = 0;
for (p = &a[0]; p < &a[N]; p++) {
    sum += *p;
}

*p++ or combining * and ++ operators

Use cases for this is creating a stack function, see c_programming_a_modern_approach

Array name == pointer

for (p = a; p < a; p++)
{
    sum += *p;
}

comparing pointers

for (p = a; p < a + N; p++) {
    sum += *p;
}

errors

int a[20];

/* ... */

while (*a != 0)
    a++; /* wrong as you are trying to make the array point somewhere else*/

p = a;
while (*p != 0)
    p++; /* correct */

tags

c

backlinks