Pointer arithmetic problem

I'm stuck at pointer arithmetics. I'm looking to move to the value that "poly_pow" and modify it. But when I use the for loop to get there, I end up modifying something else.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Implementation
// replaces the coefficient of x^power with a new coefficient
void Polynomial::changeCoefficient(const int new_coeff, const int poly_pow) {
	for (int i=0; i < poly_pow; i++) {
		coeff++;
	}
	*coeff = new_coeff;
}

// Test driver
poly_1.changeCoefficient(30,1);

// Output
Polynomial:
30x^2 // x^2 (coefficient supposed to not change)
6.94933e-310x^1 //x^1 (coefficient supposed to change to 30) 
Last edited on
Who is that "coeff"?
Oops, I fixed it :)

1
2
3
4
5
void Polynomial::changeCoefficient(const int new_coeff, const int poly_pow) {
	for (int i=0; i < poly_pow; i++) {
		*coeff-- = new_coeff;
	}
}


EDIT: Nevermind, it didn't work for other use cases. Problem still isn't solved :(

Problem solved: see @Disch answer below :)
Last edited on
This is not enough information for me to figure out what's going on.

What is 'coeff'? What does it represent? (Nevermind, I guess it's the coefficient =P )

What members do you have apart from 'coeff' in this class?

How is your output being generated? Can you show the function being used to print that output?



EDIT:

On second examination... why are you using pointer math at all? Why would you modify coeff? Wouldn't that screw up your entire object if coeff no longer points to the first coefficient in the polynomial?


Why not the more direct approach:
1
2
3
4
void Polynomial::changeCoefficient(const int new_coeff, const int poly_pow)
{
    coeff[poly_pow] = new_coeff;
}
Last edited on
'coeff' is a pointer to an array of doubles.

The following is the print function:
1
2
3
4
5
6
// prints a polynomial
void print(Polynomial poly){
	for (int i=0; i<poly.degree();i++) {
		cout << poly.coefficient(poly.degree()-i) << "x^" << poly.degree()-i << endl;
	}
}
@Disch,

You are correct. I totally overthought this :P
Let that be a lesson to you. Pointer math is pretty much always the wrong solution in C++.

There's a few exceptions, but they're very rare.
Last edited on
Topic archived. No new replies allowed.