1

This is my code, which can find highest number in an array by the pointer.

#define ELTS 5
#include <stdio.h>
#include <stdlib.h>
int main(void) {
  int i, *high, *p;
  int array[ELTS]={200,34,78,600,45};
  high=array;
  p=array;
  for ( i=1; i< ELTS; i++ ) {
      p++;
      if (*p > *high)  high = p;
  }
  printf("the highest number is %d \n", *high);
  printf("at address %p \n", high);
  printf("index %ld \n", high);
  printf("index %ld \n", array);
  printf("at index %ld of array \n", high-array);

  exit(0);
}

I also need to find the index number of this number, I did some research online. and find out I can use printf("at index %ld of array \n", high-array); to get the index of the highest number.

However, I don't understand how that works, can anyone explain it to me?

Allen Li
  • 479
  • 1
  • 5
  • 11

2 Answers2

4

In high-array, high is the address of the element you are interested in, and array is the address of the first element in the array. (array actually identifies the array, but, when used in this expression, it is automatically converted to the address of the first element.) Then, with the - operator, the two addresses are subtracted.

When addresses are subtracted, C produces a result measured in units of array elements. So, even if the array addresses are measured in bytes, the compiler computes a result by subtracting the pointers (to get the difference in bytes) and then dividing by the number of bytes in an element (to get the difference in elements).

Thus, the result of high-array is the number of elements from the start of the array to the element pointed to by high, and that is the index of that element.

(In some C implementations, the pointers might not be measured in bytes and might not be simple one-number addresses. Regardless, the C implementation performs whatever operations are necessary to produce a result that is a number of elements.)

Notes

To print pointers, convert them to void * and print them with %p:

printf("index %p \n", (void *) high);

To print the difference of two pointers, use %td:

printf("at index %td of array \n", high-array);
Community
  • 1
  • 1
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
2

Use the pointer arithmetic. The index is calculated like

high - array

The difference contains the number of elements of the type int between these two pointers.

Consider for example this statement from your program

p++;

After this statement the pointer points to the next element of the array. This statement can be rewritten like

int *q = p;
p = p + 1;

So p - q is equal to 1.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335