why do i get this compile error: " error: cannot bind non-const lvalue reference of type ‘Matrix&’ to an rvalue of type ‘Matrix’ "? - reference

Ok so i'am writting this code for an exercise we have to write a class for matrices and then to check it we use a code that the teacher wrote to check if it performes the normal operations.
And i don't get exactly where i am wrong it seems to bother the compiler that i return a type Matrix but really i dont get what is a lvalue or rvalue .
But i get this when i try to compile
anthony#anthony-linux:~/Documents/CS/Ex6$ g++ -Wall simplematrixtest.cc Matrix.cc -o simplematrixtest
simplematrixtest.cc: In function ‘int main()’:
simplematrixtest.cc:70:24: error: cannot bind non-const lvalue reference of type ‘Matrix&’ to an rvalue of type ‘Matrix’
70 | Matrix g = f.multiply(a);
| ~~~~~~~~~~^~~
In file included from simplematrixtest.cc:4:
Matrix.hh:13:18: note: initializing argument 1 of ‘Matrix::Matrix(Matrix&)’
13 | Matrix(Matrix &m);
| ~~~~~~~~^
this is my class Matrix:
#include "Matrix.hh"
#include <cmath>
#include <iostream>
using namespace std;
// Default constructor: initializes the Matrix.
Matrix::Matrix() {
nrows=0;
ncols=0;
values=0;
}
// Initializes the Matrix with rows and cols.
Matrix::Matrix(int numberOfRows,int numberOfCols) {
nrows=numberOfRows;
ncols=numberOfCols;
values = new double[nrows*ncols] ;
for (int i = 0; i < nrows*ncols; i++) {
values[i] = 0;
}
}
// Copy constructor
Matrix::Matrix(Matrix &m)
{
nrows=m.getRows();
ncols=m.getCols();
int sizeOfM=m.getRows()*m.getCols();
values = new double[sizeOfM];
for (int i = 0; i < sizeOfM; ++i) {
values[i] = m.values[i];
}
}
// Destructor - Matrix allocates no dynamic resources.
Matrix::~Matrix() {
delete[] values;
// no-op
}
// Mutators:
void Matrix::setElem(int rowIndex,int colIndex,double val){
values[rowIndex*ncols+colIndex]=val; /*See Jasper i listen to what you say ! No return for a void function :) */
}
void Matrix::subtract(Matrix &m) {
for (int i = 0; i < nrows*ncols; i++) {
values[i] -=m.values[i];
}
}
void Matrix::add(Matrix &m) {
for (int i = 0; i < nrows*ncols; i++) {
values[i] +=m.values[i];
}
}
Matrix Matrix::multiply(Matrix &m) {
if(ncols!=m.getRows()){
cout << " Error :invalid matrix multiplication"<< endl;
Matrix ret(0,0);
return ret;
}
else{
Matrix ret(nrows,m.getCols());
for (int rowIndex = 0; rowIndex < ret.nrows; rowIndex++) {
for (int colIndex = 0; colIndex < ret.ncols; colIndex++) {
for(int count=0; count <= ncols; count++) {
ret.values[rowIndex*ncols+colIndex] +=(values[rowIndex*ncols+(count)]*m.values[count*ncols+colIndex]);
}
}
}
return ret;
}
}
// Accessors:
int Matrix::getRows() {
return nrows;
}
int Matrix::getCols() {
return ncols;
}
double Matrix::getElem(int rowIndex,int colIndex){
return values[rowIndex*ncols+colIndex];
}
bool Matrix::equals(Matrix &m) {
if(m.getRows()!=nrows||m.getCols()!=ncols){return false;}
for (int i = 0; i < nrows*ncols; i++) {
if(values[i] !=m.values[i]){return false;}
}
return true;
}
Apparently the problem is in multiply here is the test code
#include <iostream>
using namespace std;
#include "Matrix.hh"
// Have some fun playing with a Matrix!
int main(void) {
// Create a new matrix with two rows and three columns
Matrix a(2, 3);
// Print out some information about the size of this matrix:
cout << "Matrix a is " << a.getRows() << " rows tall." << endl;
cout << "Matrix a is " << a.getCols() << " columns wide." << endl;
// Print out the contents of this matrix (should be all zeroes!):
for(int r = 0; r < a.getRows(); r++) {
for(int c = 0; c < a.getCols(); c++) {
cout << "Element (" << r << ", " << c << ") = " << a.getElem(r,c) << endl;
}
}
// Fill in a few values
a.setElem(1, 2, -5280); // bottom right element is now -5280
a.setElem(0, 1, 123); // top center element is now 123
// Create an identical copy of this matrix
Matrix b = a;
// Change the original matrix some more
a.setElem(1, 2, 555); // bottom right element is now 555
// Examine some elements of each matrix
cout << "(1,2) of a = " << a.getElem(1,2) << " [should be 555]" << endl;
cout << "(1,2) of b = " << b.getElem(1,2) << " [should be -5280]" << endl;
// So if a and b are different, let's copy a into a new matrix and add b to it:
Matrix c = a;
c.add(b);
// Now let's copy c into another new matrix, d, and subtract a from it:
Matrix d = c;
d.subtract(a);
// Hmm... that means d should be b, no?
if (d.equals(b)) {
cout << "Yay! d = b!" << endl;
} else {
cout << "Uh-oh! Something went wrong, d isn't b!" << endl;
}
// Let's create a tiny 0 by 0 matrix using the default constructor:
Matrix e;
cout << "0x0 matrix e is " << e.getRows() << " by " << e.getCols() << endl;
// Of course, e and d are different, since they have different sizes!
if(!e.equals(d)) {
cout << "e and d are indeed different!" << endl;
} else {
cout << "Oh well, back to the drawing board...." << endl;
}
Matrix f(2,2);
f.setElem(0, 0, 2.0);
f.setElem(1, 0, 3.0);
f.setElem(0, 1, 5.0);
f.setElem(1, 1, 7.0);
Matrix g = f.multiply(a);
if (g.getElem(1, 2) == 3885.0) {
cout << "Multiply seems to work!" << endl;
} else {
cout << "Error in multiply() !" << endl;
}
// Okay, enough of this; destroy all those matrices and end the program:
return 0;
}
If i write
Matrix g = a ;
f.multiply(a);
The code compiles without any problem so it is a problem with this line: Matrix g =f.multiply(a);

Related

How to debug Run-Time Check Failure #2 - Stack around the variable 'newString' was corrupted

This is a function to convert a long string (sentence) into a vector of strings. From the error, it seems obvious that the char ptr newString is causing some access violation, run-time issues. Probably it's length is the root cause?
Also, please note that the output of the function is just coming as expected, but with the run-time error occurring.
vector<string> convertStrgToStrVect(char *inString)
{
unsigned int end = 0, start = 0, i = 0, len = 0, j = 0;
char *inStr = inString, *s;
char newString[] = "";
vector<unsigned int> startLenVect, endLenVect, strLenVect;
vector<unsigned int> :: iterator itr1, itr2;
vector<string> stringVect;
vector<string> :: iterator itr3;
s = inStr;
// Add an extra space an the end of the string
for( i = 0; i < strlen(s); i++)
{
}
s[i] = ' ';
i++;
s[i] = '\0';
cout << s << endl;
cout << strlen(s) << endl;
// Create vectors for start and end indexes to split the words separated by a space
for( i = 0; i < strlen(s); i++)
{
if(s[i] != ' ')
{
end++;
len = end - start;
}
else
{
endLenVect.push_back(end);
startLenVect.push_back(start);
strLenVect.push_back(len);
end = i+1;
start = i+1;
}
}
cout << "startLenVect: ";
for(itr1 = startLenVect.begin(); itr1 != startLenVect.end(); itr1++)
{
cout << *itr1 << " ";
}
cout << "endLenVect: ";
for(itr1 = endLenVect.begin(); itr1 != endLenVect.end(); itr1++)
{
cout << *itr1 << " " << endl;
}
for(itr1 = startLenVect.begin(), itr2 = endLenVect.begin(); itr1 != startLenVect.end(); itr1++, itr2++)
{
strcpy(newString, "");
for(i = *itr1, j = 0; i < *itr2; i++, j++)
{
newString[j] = s[i];
}
newString[j] = '\0';
stringVect.push_back(newString);
}
for(itr3 = stringVect.begin(); itr3 != stringVect.end(); itr3++)
{
cout << "stringVect: " << *itr3 << endl;
}
return stringVect;
}

Can't initialize float array with {0}

My Compiler gives runtime error when I initialize the float array in Veccreator function. I am here posting just a sample of what my code looks like.
#include<iostream>
using namespace std;
#define SIZE 1000
class Vector
{
private:
float vecarray[SIZE];
public:
void VecCreator(int dimension)
{
vecarray[SIZE]= { 0 };
cout << "Enter " << dimension << " digits" << endl;
for (int i = 0; i < dimension; i++)
{
cin >> vecarray[i];
}
}
};
int main(void) {
Vector obh;
obh.VecCreator(2);
}
But it works fine with this:`
#include<iostream>
using namespace std;
#define SIZE 1000
class Vector
{
private:
float vecarray[SIZE]= {0};
public:
void VecCreator(int dimension)
{
cout << "Enter " << dimension << " digits" << endl;
for (int i = 0; i < dimension; i++)
{
cin >> vecarray[i];
}
}
};
int main(void) {
Vector obh;
obh.VecCreator(2);
}
Please tell me why the first code is giving error.
Look at the second answer here:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/14e7318e-6fff-4d68-a823-9cbe7b7bc20a/debugging-runtime-check-failure-2-stack-around-the-variable-loggerthread-was-corrupted?forum=vcgeneral
why not do it like here below? i mean if you want to put values in there, why initially put 0 in there?
private:
float vecarray[SIZE];
public:
void VecCreator(int dimension)
{
cout << "Enter " << dimension << " digits" << endl;
for (int i = 0; i < dimension; i++)
{
cin >> vecarray[i];
}
}

Why the variable 'len_' never been change in the function ca_time

void ca_time(int *arr,int &len_) //the variable len_'s value always is 0
{
cout << "You only got five seconds to type the number 1~5,,ready go,,\n";
_sleep(5000);
cout << "Sorry time out!!\n";
cout << "Ok, here is your greads:\n";
for(int i = 0; i < len_; i ++)
{
cout << arr[i] << " ";
}
cout << endl;
cout <<"-->" << len_ << endl;
return;
}
void fun_type(int *arr,int &len_)
{
memset(arr,'\0',sizeof(arr));
for(; len_ < 5; len_ ++)
{
cin >> arr[len_];
}
}
int main()
{
int arr[100];
int len = 0;
thread time(ca_time,arr,len);
time.detach();
fun_type(arr,len);
system("pause");
return 0;
}
But it work when changed the quote to the address(point variable).Why?
Somebody say that's a IED's bug?But I don't think so .So What the hell?

finding largest and smallest numbers in an array

i have to find the max and min value in array of random numbers... here is my code:
#include<iostream>
using namespace std;
void populateArray();
int findMin();
int findMax();
int computeTotal();
int arr[50];
int small, big;
void main()
{
big = small = arr[0];
populateArray();
findMin();
findMax();
computeTotal();
system("pause");
}
void populateArray()
{
for (int i = 0; i < 48; i++)
{
arr[i] = rand() % 1000;
cout << arr[i] << " ";
}
cout << endl;
}
int findMin()
{
for (int i = 0; i < 48; i++)
{
if (arr[i] < small)
{
small = arr[i];
}
cout << "The smallest number is " << small << endl;
return 0;
}
}
int findMax()
{
for (int i = 0; i < 48; i++)
{
if (arr[i] > big)
{
big = arr[i];
}
}
cout << "The biggest number is " << big << endl;
return 0;
}
int computeTotal()
{
int sum = 0;
sum = big + small;
cout << "Total= " << sum << endl;
return 0;
}
But the problem is that it does not display the minimum and maximum value from the array... it displays minimum value 0 and max 995 which are not included even in the array..
any help??

logic error in prime # program. The program just ends after I answer the prompt so I can't see the numbers

//Purpose: Display first 'n' (user chosen) number if emirps to the console, five per line.
//Note: An "emirp" is a prime number that is also prime when reversed.
#include <iostream>
using namespace std;
bool isPrime(int value); //Prototyle for "prime number function"
int reverse (int value2); //Prototype for "emirp function"
int main()
{
//Ask the user for a positive number
cout << "Please enter a positive number: ";
int n;
cin >> n;
//Reject negative value input
if ( n < 1)
{
cout << "INVALID NUMBER \n";
}
else
{
//Calculate all emirps up to 'n'.
int test = 0;
int number = 2;
while (test < n)
{
if (isPrime(number) && reverse(number))
{
cout << "\n" << reverse(number) << "\t\t\t";
test++;
}
else
{
test++;
}
}
}
system("pause");
return 0;
}
bool isPrime(int value)
{
//If value is prime, the remainder (count) will be zero twice--for 1 and itself.
int divisor = 1;
int count = 0;
int prime = 0;
if (value % divisor == 0)
{
count++;
++divisor;
}
if (count = 2)
{
return true;
}
else
{
return false;
}
}
int reverse(int value2)
{
//reverse the number
value2*=10;
value2 = value2 %10;
value2/=10;
//same procedure as prime function
int divisor2 = 1;
int count2 = 0;
int emirp = 0;
if (value2 % divisor2 == 0)
{
count2++;
++divisor2;
}
if (count2 = 2)
{
int emirp = value2;
}
return emirp;
}
How does this even build?
if (count = 2)
{
...
}
Also:
your reverse function just returns an int, what do you expect
if (isPrime(number) && reverse(number)) to do with that result?
It's not a good way of working to do the whole calculation again btw:
cout << "\n" << reverse(number) << "\t\t\t"; //you already did this in your "check"
Edit:
And no wonder it doesn't work.
You check the number-value (2) every time, not n
If it is just about viewing the console output :
Press CTRL+F5 to run application in Visual studio.
just provide a getch()in main() function
And your code syntax is not in a right way :
if (count = 2) //count ==2
{
return true;
}
if (isPrime(number) && reverse(number))
{
cout << "\n" << reverse(number) << "\t\t\t";
test++;
}
will call reverse() 2 times.
modify it something like ;
int RevNum = reverse(number);
if (isPrime(number) &&RevNum)
{
cout << "\n" << RevNum << "\t\t\t";
test++;
}

Resources