-2

I'm writing a class to add, subtract and multiply polynomials (going on 1 week now!). Anyway, the code compiles, but I'm seeing what appears to be memory addresses in the output.

I can't figure out why this is happening.

Can anyone steer me in the right direction?

Thanks in advance for taking a look! Ryan

The code:

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

class Poly
{
private:

//  int ord;                            // the order of the polynomial
//  int coeff[100];

public:

    int ord;                            // the order of the polynomial
    int coeff[100];


    int a, b, c;
    Poly();                             // constructor
    Poly addition(Poly b);              // adds 2 polynomials
    Poly subtraction(Poly b);           // subtracts 2 polynomials
    Poly multiplication(Poly b);        // multiplies 2 polynomials
    int evaluate(int);                  // uses Horner's method to compute and return the polynomial evaluated at x
    Poly differentiate();               // 
    void set(int, int);                 // mutator function
    int order();
    void print();                       // prints the results
};

Poly::Poly()                            // the default constructor
{
    for (int i = 0; i < 100; i++)
    {
        coeff[i] = 0;
    }
}

void Poly::set(int a, int b)            // mutator function
{
    // coeff = new Poly[b + 1];
    coeff[b] = a;
    ord = order();
}

int Poly::order()
{
    int d = 0;
    for (int i = 0; i < 100; i++)
        if (coeff[i] != 0) d = i;
        return d;
}

void Poly::print()
{
    int coeff[] = { 0 };

    for (int i = 99; i >= 0; i--)
    {
        if (coeff[i] != 0)
        {
            cout << coeff[i] << "x^" << i << " ";
        }
    }
}

int Poly::evaluate(int x)
{
    int p = 0;
    for (int i = ord; i >= 0; i--)
        p = coeff[i] + (x * p);
    return p;
}

Poly Poly::differentiate()
{
    if (ord == 0)
    {
        Poly t;
        t.set(0, 0);
        return t;
    }

    Poly deriv;
    deriv.ord = ord - 1;

    for (int i = 0; i < ord; i++)
        deriv.coeff[i] = (i + 1) * coeff[i + 1];
    return deriv;
}

Poly Poly::addition(Poly b)
{
    Poly a = *this;
    Poly c;

    for (int i = 0; i <= a.ord; i++)
        c.coeff[i] += a.coeff[i];
    for (int i = 0; i <= b.ord; i++)
        c.coeff[i] += b.coeff[i];

    c.ord = c.order();

    return c;
}

Poly Poly::subtraction(Poly b)
{
    Poly a = *this;
    Poly c;

    for (int i = 0; i <= a.ord; i++)
        c.coeff[i] += a.coeff[i];
    for (int i = 0; i <= b.ord; i++)
        c.coeff[i] -= b.coeff[i];

    c.ord = c.order();

    return c;
}

Poly Poly::multiplication(Poly b)
{
    Poly a = *this;
    Poly c;

    for (int i = 0; i <= a.ord; i++)
    for (int j = 0; j <= b.ord; j++)
        c.coeff[i + j] += (a.coeff[i] * b.coeff[j]);
    c.ord = c.order();
    return c;
}

int main()
{
    Poly a, b, c, d;
    a.set(7, 4);                    //  7x^4
    a.set(1, 2);                    //  x^2

    b.set(6, 3);                    //  6x^3
    b.set(-3, 2);                   //  -3x^2

    c = a.subtraction(b);           //  (7x^4 + x^2) - (6x^3 - 3x^2)

    c.print();

//  cout << "\n";

//  d = c.differentiate().differentiate();

//  d.print();

//  cout << "\n";

//  cout << c.evaluate(2);          //  substitute x with 2
//  cin.get();

    return 0;
}

EDIT

This is what I'm seeing. Any idea how to remedy this???

enter image description here

user3407254
  • 55
  • 1
  • 2
  • 8
  • Your `Poly` class does not initialize the various members in the constructor -- all it does is make the `coeff` array all 0, and that is *not* enough. For example, your code as it stands doesn't prevent anyone from using `ord` that hasn't been initialized: `int main() { Poly p; p.differentiate(); }` Real simple code required to break your class... – PaulMcKenzie Aug 01 '14 at 22:14
  • Remove `int a, b, c;` from the class definition, you never use those and since you are using the same names for local variables, it increases the risk of a mistake – M.M Aug 01 '14 at 23:19
  • Use `std::vector` for your coefficients, not an array. Preallocating 100 either wastes space (for small polynomials) or results in buffer overflow for polynomials with more than 100 terms. – Thomas Matthews Aug 01 '14 at 23:21
  • Is the assignment to use an array for coefficients? You could use a linked list (`std::list`) and only push in terms that exist. For example, there are common polynomials that only use terms with even exponents. This would waste half of your memory space with an array implementation. – Thomas Matthews Aug 01 '14 at 23:33
  • Does my code not work for you? – Naseef Chowdhury Aug 02 '14 at 02:11

3 Answers3

7

As far as I can tell, you shouldn't be seeing anything at all.

The print() method start with

int coeff[] = { 0 };

This will hide the member variable coeff, and will be set to 0,

James Curran
  • 101,701
  • 37
  • 181
  • 258
  • This results in an out-of-bound access, since that local `coeff` only has *one* element. – dyp Aug 01 '14 at 21:58
  • 3
    The whole `print()` method is scary. The `for` loop spends its entire run time (99 iterations!) accessing out-of-bounds memory! – Doug Aug 01 '14 at 22:04
0

It would help if you posted some of the output you see. Try wrapping every expression outputted in parentheses. For example, cout << (coeff[i]) instead of cout << coeff[i]. Also, in your print method you write int coeff[] = {0}, despite having coeff already declared as a member variable.

  • This was not the root cause of the problem. You can suggest your opinion in comment not in answer and I don't think this was an answer. – Naseef Chowdhury Aug 01 '14 at 22:18
  • I added an image of the console output. Also, I amended int coeff[] = {0} to int coeff[100] = {0} and added this to the constructor (instead of in the print() function. Still confused as to why the output is garbage. – user3407254 Aug 01 '14 at 23:16
0

Your code will work. Just do the following change in your "Poly::Print()" method

void Poly::print()

    {
        //int coeff[] = { 0 };

        for (int i = 99; i >= 0; i--)
        {
            if (coeff[i] != 0)
            {
                cout << coeff[i] << "x^" << i << " ";
            }
        }
    }

or you can copy this code and replace it with your current "Poly::Print()" method.

The root cause of the problem was you were printing an array of local variable, which you have declared in the "Poly::print()" method. And this array only have one element according to your declaration. Because

int coeff[] = {0};

the above code actually creates an array with size 1.

Naseef Chowdhury
  • 2,357
  • 3
  • 28
  • 52