Edin Mahmutovic
Edin Mahmutovic

Reputation: 117

Expected expression in C

I am trying to test an algorithm in C, but when trying to call the function, I get the error "Expected expression" at the line where I call the function in my main function. Can somebody spot the mistake that is made?

#include <math.h>
#include <stddef.h>

int fwsubst(
            unsigned long n,
            double alpha,
            double **R,  /* two-dimensional array, row-major */
            double *b    /* one-dimensional array */
);

int main(void){


    fwsubst(2 ,5.0,{{2.0,2.0},{4.0,2.8}}, {1.0, 9.6});

    return 0;
}

int fwsubst(
            unsigned long n,
            double alpha,
            double **R,  /* two-dimensional array, row-major */
            double *b    /* one-dimensional array */
){
    double x;

    for (size_t k = 0; k < n; k++) {
        double sum = 0.0;
        for (size_t i = 0; i < k; i++) {
            sum +=  b[i] * R[i][k];
        }
        x = (b[k] - sum)/(alpha + R[k][k]);
        if (!isfinite(x))
            return -1;
        if(alpha + R[k][k] == 0)
            return -1;
        b[k] = x;
    }
    return 0;
}

Upvotes: 0

Views: 266

Answers (2)

chux
chux

Reputation: 154176

OP's code is invalid

//             v-------------------v  v--------v Invalid
fwsubst(2 ,5.0,{{2.0,2.0},{4.0,2.8}}, {1.0, 9.6});

With C99, code can use compound literals.

A postfix expression that consists of a parenthesized type name followed by a brace enclosed list of initializers is a compound literal. C11dr §6.5.2.5 3

int fwsubst(unsigned long n, double alpha, double **R, double *b);

int main(void) {
  fwsubst(2, 5.0,
  //  v------------------------------------------------------------v  nested literal
  //                 v--------------------v, v--------------------v  literal
      (double *[2]) {(double[2]) {2.0, 2.0}, (double[2]) {4.0, 2.8}},
      (double[2]) {1.0, 9.6});
  //  ^--------------------^ literal
}

No need to change the function definition.

Upvotes: 3

dbush
dbush

Reputation: 224532

That's not the proper syntax for an array literal. You need:

fwsubst(2 ,5.0,(double[2][2]){{2.0,2.0},{4.0,2.8}}, (double[2]){1.0, 9.6});

And you need to change the function definition to match, since a double[2][2] doesn't convert to a double ** but to a double (*)[2]:

int fwsubst(
            unsigned long n,
            double alpha,
            double R[n][n],  /* two-dimensional array, row-major */
            double b[n]      /* one-dimensional array */
);

...

int fwsubst(
            unsigned long n,
            double alpha,
            double R[n][n],  /* two-dimensional array, row-major */
            double b[n]      /* one-dimensional array */
){
    ...

Upvotes: 2

Related Questions