0

I need to find and print the index of the highest value in the array using pointers. My professor said it's possible to do with only the defined integers below (no counters or other valuables).

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
int array[100], size, *MAX, *pi;
srand(time(NULL));
MAX = array;

printf("Insert array size:\n");
scanf("%d", &size);

for(pi=array; pi<array+size; pi++)
{
    *pi = ( rand()%100 ) + 1;
}

printf("\nArray elements:\n");
for(pi=array; pi<array+size; pi++)
    printf("%d\t", *pi);

for(pi=array+1; pi<array+size; pi++)
    if(*pi>*MAX)
{
    MAX = pi;
}

printf("\n\nMax is %d.", *MAX);
}
4
  • Record the pointer of the new max value, at the same time you record the new max value. Then its index will be the subtraction of pointers pimax - niz. But unfortunately what niz is, is unknown in your code. Commented Oct 11, 2016 at 19:54
  • MAX points to the max value in the array and you have a pointer to the start of the array and the memory is contiguous so you can subtract the MAX pointer from the array pointer to get the bytes and divide by the size of the stored datatype: (MAX-array) / sizeof(int) Commented Oct 11, 2016 at 20:01
  • 1
    @Iverelo don't divide by the size. Pointer arithmetic takes care of that for you. Oops in my first comment MAX is already the pointer to the max element, not its value. So its index is MAX - array but niz is undefined. Commented Oct 11, 2016 at 20:02
  • I do apologise, niz is array in this case, translated to english. Commented Oct 11, 2016 at 20:18

1 Answer 1

1

I'll answer my own question if anyone stumbles on it. Thanks to Weather Vayne.

After determining the max value in the array, you find the index like this:

printf("%d", MAX - array);

The index shows places from 0 to n-1, so you can add +1 to make it show places from 1 to n (n is the number of elements in the array):

printf("%d", MAX - array + 1);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.