I'm solving a problem for class in C where I return the biggest value from an unsorted array and the index of that value gets stored in the pointer index_ptr.
Here is the code I built:
int get_biggest_index(int array[], size_t array_size, int *index_ptr){
int max = array[0], index;
for (int i = 0; i < array_size-1; i++){
if (array[i+1] > max){
max = array[i];
index = i;
}
}
index_ptr = &index;
printf("idx: %d\n", *index_ptr); //purely for testing
return max;
}
I know the above works as intended for returning the highest value, but running it in this context:
int main() {
int arr[5] = {4, 7, 3, 9, 5};
size_t arr_size = 5;
int *idx;
printf("biggest value in array arr => %d\n", get_biggest_index(arr, arr_size, idx));
printf("idx of biggest value => %d", *idx);
return 0;
}
The output is:
idx: 3
max value in array arr => 9
idx of max value => -98693133
Can someone explain me specifically why this is happening in regards to the value of the pointer and how to fix it?
I'll also be happy to listen to any other suggestions regarding the rest of the code as I'm sure it can be better.
Thank you very much for the help!