-1
#include <stdio.h>

void triU(double **U, double *b, int n)
{
    n--;
    b[n] /= U[n][n];
    for(int i = n - 1; i >= 0; i--)
    {
        double aux_sum = 0;
        for(int j = i + 1; j <= n; j++)
            aux_sum += (U[i][j] * b[j]);
        b[i] = (b[i] - aux_sum) / U[i][i];
    }
}

int main()
{
    int n = 3;
    double U[][n] = {{5, -5, 10}, {0, 2, 4}, {0, 0, -1}};
    double b[] = {25, 16, -2};
    triU(U, b, n);
    for(int i = 0; i < n; i++)
        printf("%le \n", b[i]);
    return 0;
}

This is the code for what I am trying to do. I am supposed to make a method with the parameters written in that way to pass the two matrices.

However I keep getting the following error.

triU.c: In function ‘int main()’:
triU.c:21:10: error: cannot convert ‘double (*)[n]’ to ‘double**’
   21 |     triU(U, b, n);
      |          ^
      |          |
      |          double (*)[n]
triU.c:3:20: note:   initializing argument 1 of ‘void triU(double**, double*, int)’
    3 | void triU(double **U, double *b, int n)
      |           ~~~~~~~~~^

I would appreciate any help on how I am supposed to pass arrays by pointers in C. Thank you very much.

0

1 Answer 1

0

In this call of the function triU:

triU(U, b, n);

the two-dimensional array U is implicitly converted to pointer to its first element of the type double ( * )[3]. But the corresponding function parameter has the type double ** and there is no implicit conversion between the pointer types. So the compiler issues a message.

If your compiler supports variable length arrays (and your compiler support VLAs) then declare the function like:

void triU( size_t n, double ( *U )[n], double *b );

or:

void triU( size_t n, double U[][n], double *b );

and call it like:

triU( n, U, b );

Otherwise declare the function like:

void triU( double ( *U )[3], double *b, size_t n );

or:

void triU( double U[][3], double *b, size_t n );

and call it like:

triU( U, b, n );

Pay attention to that this for loop:

    for(int j = i + 1; j <= n; j++)
        aux_sum += (U[i][j] * b[j]);

can invoke undefined behavior when j is equal to n because the valid range of indices is [0, n).

Also bear in mind that the length modifier in the format string in this call:

printf("%le \n", b[i]);

is redundant and has no effect. You may write:

printf("%e \n", b[i]);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.