Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Segmentation Fault from function that returns the maximum of an array

I just have a function that finds out the maximum value of an array of integers, but I get a segmentation fault, which I can't find because the compiler doesn't show me the line of the error.

This is my C code:

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

//Funktion ermittelt den größten Wert eines Arrays
int groesstesElement(int **arrayPointer){
    int max = 0;
    for (int i = 0; i < 3; i++) {
        if (*arrayPointer[i]>max) {
            max = *arrayPointer[i];
        }
    }
    return max;
}


int main (int argc, char **argv) {
    int array[4]={1,2,3,4};
    int *ptr = array;
    int z = groesstesElement(&ptr);
    printf("%d\n", z);

    return EXIT_SUCCESS;
}

I use macOS and VSC.

like image 705
chrizzla Avatar asked Dec 30 '22 19:12

chrizzla


1 Answers

In C, array indexing [] has higher precedence than pointer de-referencing *: https://en.cppreference.com/w/c/language/operator_precedence

Some parentheses fix the segfault.

if ((*arrayPointer)[i]>max) {
    max = (*arrayPointer)[i];
}
like image 120
Rhythmic Fistman Avatar answered Jan 05 '23 16:01

Rhythmic Fistman