c++ - get function not returning what i expect -
i trying create function in class return take i, j argument , return value of located @ object(i, j).
so far in function converting i, j equivalent in 1d array * (number of columns) + j, in code equal 5. next want show value @ location 5 in array. seems return first value of array, not location 5 value. ideas going wrong? using pointer in wrong way? full program below:
#include <iostream> using namespace std; class mymatrix{ public: //default constructor set member variables null states mymatrix(); mymatrix(int sizer, int sizec, double * input_data); ~mymatrix(); //destructor //member functions int get(int i, int j); private: int m; //rows int n; //columns double * data; }; int main(){ const int rows = 3; const int columns = 2; double * userinput; cout << "the array 3*2, or 6 elements." << endl; userinput = new double[rows*columns]; double temp; (int = 0; < rows*columns; i++){ //let user type in array cout << "please enter value" << << endl; cin >> temp; *(userinput + i) = temp; } mymatrix objecta(rows, columns, userinput); //creating object specifications cout << "the value of objecta 2,1 is: " << objecta.get(2, 1) << endl; return 0; } mymatrix::mymatrix(){ cout << "mymatrix constructor lets go" << endl; m = 0; n = 0; data = 0; } mymatrix::mymatrix(int sizer, int sizec, double * input_data){ cout << "mymatrix::mymatrix(int sizer, int sizec, double * input_data) called." << endl; //showing constructor working :) m = sizer; n = sizec; data = new double[m*n]; (int = 0; < m*n; i++){ data[i] = *input_data; } cout << "the items have entered are:" << endl; //printing out array showing array filled (int = 0; < m*n; i++){ cout << << "item is: " << *(input_data + i) << endl; } } int mymatrix::get(int i, int j){ cout << "getfunction happening" << endl; //val should k [k = * n + j] int val = 0; val = * n + j; //n columns, m rows derp cout << "val equal to: " << val << endl; //so val 5 //how display @ location 5 in object return data[val]; // shouldnt return 5th element in data? } mymatrix::~mymatrix(){ cout << "mymatrix::~mymatrix() invoked" << endl; //showing destructa function working delete[] data; //the memory management }
use data[i] = input_data[i]
instead data[i] = *input_data
, , add delete [] userinput
free memory or memory leak.
Comments
Post a Comment