C - Pointer math in array

Introduction

The following code declares an int array and displays that array's location in memory.

Demo

#include <stdio.h> 

int main() //from  www . j av a 2s  .  c  o m
{ 
    int array[5] = { 2, 3, 5, 7, 11 }; 

    printf("'array' is at address %p\n",&array); 
    printf("'array' is at address %p\n",array); 
    return(0); 
}

Result

The & is important for individual variables.

But for arrays, it's optional.

What happens when you increment a pointer?

my_pointer++; 

The address stored in a pointer variable is incremented by one unit, not by one digit.

What's a unit?

It depends on the variable type. If pointer is a char pointer, indeed the new address could be 0x8001.

But if my_pointer were an int or a float, the new address would be the same as

0x8000 + sizeof(int) 

or

0x8000 + sizeof(float) 

On most systems, an int is 4 bytes, so you could guess that my_pointer would equal 0x8004 after the increment operation.

Demo

#include <stdio.h> 

int main() /*  ww  w.j a  v a  2  s. c o m*/
{ 
    int numbers[10]; 
    int x; 
    int *pn; 

    pn = numbers;       /* initialize pointer */ 

/* Fill array */ 
  for(x=0;x<10;x++) 
    { 
        *pn=x+1; 
        pn++; 
    } 

/* Display array */ 
    for(x=0;x<10;x++) 
        printf("numbers[%d] = %d\n", x+1,numbers[x]); 

    return(0); 
}

Result

Related Topic