0

I'm trying to implement polynomials in C but Im having an issue with arrays and setting values. Im bad at C, please explain why this is happening: I run this, it says that p.coefs[1] is 0.0 instead of 3.0 as intended.

#include <stdio.h>
#include <assert.h>

int main()
{
    #define MAX_DEG 10

    typedef struct Polynomial Polynomial;

    struct Polynomial {
        int deg;
        double coefs[MAX_DEG];
    };

    Polynomial ply_create(int deg) {
        assert(deg >= 0 && deg <= MAX_DEG);
        Polynomial poly;
        poly.deg = deg;

        return poly;
    }

    void ply_set_coef(Polynomial poly, int i, double val) {
        poly.coefs[i] = val;
    }

    Polynomial p = ply_create(1);
    p.coefs[0] = 1.0;
    ply_set_coef(p, 1, 3.0);

    printf("p.coefs[0] is %f and p.coefs[1] is %f", p.coefs[0], p.coefs[1]);


    return 0;
}

I was previously using malloc and made p.coefs a pointer to a double. In this case I did not have any problem.

Ceeerson
  • 189
  • 8
  • 6
    C passes parameters by value. `poly` in `ply_set_coef` is a copy of `p` in `main`, not `p` itself. You modify the copy. – DYZ May 03 '20 at 04:28
  • Does this answer your question? [Why does call-by-value example not modify input parameter?](https://stackoverflow.com/questions/10959694/why-does-call-by-value-example-not-modify-input-parameter) – DYZ May 03 '20 at 04:29
  • 1
    Oh so if make it return the copy or if I change the function to pass by reference then I'll be good? – Ceeerson May 03 '20 at 04:30
  • yes this makes sense, I just forgot. Thank you for helping me from going crazy – Ceeerson May 03 '20 at 04:30
  • 1
    In C, I don't think you can pass by reference. See [this](https://stackoverflow.com/a/30519731). – kiner_shah May 03 '20 at 04:46
  • C doesn't support nested functions. Are you using a `gcc` extension? – Tom Karzes May 03 '20 at 06:46

0 Answers0