简体   繁体   中英

Why does adding brackets when invoking this function breaks my program?

My intention here was to make a simple program that would output the highest difference between two consecutive elements in an array, and my question is, why when add the "[ ]" in the line marked breaks the program (it works fine if I take them out).

#include <stdio.h>
#include <math.h>
#define EPSILON 0.000001
#define DIM     5

double maxDif(double vector[]);

int
main(){
    double vec[DIM]={3,5,7,23,0};
    double result;
    result=maxDif(vec[]);  /* <-- problem here */
    printf("The largest diff between 2 consecutive elements is: %g \n", result);
    return 0;
}

double
maxDif(double vector[]){
    double retVal=0;
    int i=0;
    if(fabs(vector[0]>EPSILON))
        while(fabs(vector[i++]>EPSILON))
            if((vector[i]-vector[i-1]>retVal))
                retVal=vector[i]-vector[i-1];
    return retVal;
}

When you do maxDif(vec) you passing the array (or more specifically, a pointer to the first element of the array) into the function maxDif . The definition of this function matches this call.

Calling a function like maxDif(vec[]) is invalid syntax. An empty pair of braces is only valid when declaring an array (and also initializing it if it's not a function parameter, or if it's the last field in a struct ), not when accessing it.

This is not how you need to send vec as argument. Send it like so: **result=maxDif(vec);

Explanation: vec is an array, and when you pass it as an argument you pass the address of it. The compiler already knows it's an array so the [] are not needed, moreover - they are invalid syntax, as you learned

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM