Newbie - matrix addition implementation in c++ - c++

Hello i'm trying to program the addition of 2 matrices into a new one (and it does when i run the program step by step) but for some reason VS 2010 gives me an access error after it does the addition.
Here is the code.
#include <iostream>
#include <cstdio>
#include <conio>
using namespace std;
class operatii
{
typedef double mat[5][5];
mat ms,m1,m2;
int x1,x2,y1,y2;
public:
void preg();
int cit_val();
void cit_mat(int&,int&,double[5][5]);
void suma();
void afisare(int&,int&,double[5][5]);
};
void operatii::preg()
{
cit_mat(x1,y1,m1);
cit_mat(x2,y2,m2);
suma();
afisare(x1,y1,ms);
}
int operatii::cit_val()
{
int n;
cin>>n;
return n;
}
void operatii::cit_mat(int& x,int& y,double m[5][5])
{
char r;
cout<<"Matrice patratica? Y/N ";
cin>>r;
if ((r=='y')||(r=='Y'))
{
cout<<"Numar linii si coloane: ";
x=cit_val();
y=x;
}
else
{
cout<<"Numar linii: ";
x=cit_val();
cout<<"Numar coloane: ";
y=cit_val();
}
for (int i=1;i<=x;i++)
for (int j=1;j<=y;j++)
cin>>m[i][j];
}
void operatii::suma()
{
if ((x1==x2)&&(y1==y2))
for (int i=1;i<=x1;i++)
for (int j=1;i<=y1;j++)
ms[i][j]=m1[i][j]+m2[i][j];
else cout<<"Eroare";
}
void operatii::afisare(int& x,int& y,double m[5][5])
{
cout<<endl;
for (int i=1;i<=x;i++)
{
for (int j=1;j<=y;j++)
cout<<m[i][j];
cout<<endl;
}
}
void main()
{
operatii matrice;
matrice.preg();
system("PAUSE");
}
Any kind of help would be apreciated.

Arrays are 0-based in c++.
Change your various variants of for (somevar=1; somevar<=something) to for (somevar=0; somevar<something)
You're writing past the end of your arrays, which overwrites stack return address, leading to a return to nonexecutable code, again leading to an access violation.
Also,
for (int j=1;i<=y1;j++)
I think you want to use j not i here. Such errors are much easier to see if you use longer and more distinct variable names than "i" and "j", such as e.g. "Line" and "Column"

Related

Linked List - Adding/Displaying using a vector

I have a homework to do but I don't know what's the problem with the displaying function.. I have a vector use to make more linked list (it's a part of the homework).. that's the code:
#include <iostream>
using namespace std;
#define MAX_LIST 100
struct nod {
int info;
nod* urm;
};
nod* liste[MAX_LIST];
void citesteListaSimpla(nod* liste[MAX_LIST],int nrListe);
void afisareListaSimpla(nod* liste[MAX_LIST],int nrListe);
int main()
{
unsigned int nrListe;
cout << "List numbers: ";
cin>>nrListe;
cout<<endl;
citesteListaSimpla(liste,nrListe);
afisareListaSimpla(liste,nrListe);
}
void citesteListaSimpla(nod* liste[MAX_LIST],int nrListe)
{
for(int i=0; i<nrListe; i++)
{
unsigned int nrElemente;
cout<<"Numbers of the list "<< i+1 << ": ";
cin>>nrElemente;
int element;
liste[i]=NULL;
nod* liste[nrListe];
for(int j=1; j<=nrElemente; j++)
{
cout<<"Number "<<j<<": ";
cin>>element;
liste[nrListe]=new nod;
liste[nrListe]->info=element;
liste[nrListe]->urm=liste[i];
liste[i]=liste[nrListe];
}
}
}
void afisareListaSimpla(nod* liste[MAX_LIST],int nrListe)
{
for(int i=0; i<nrListe; i++)
{
nod* liste[nrListe];
liste[nrListe]=liste[i];
while(liste[nrListe]!=NULL)
{
cout<<liste[nrListe]->info<<", ";
liste[nrListe]=liste[nrListe]->urm;
}
}
}
And if I run it it looks like this:
How I make the program to show me the linked list ? ..
On line 35 and 52 you're re-declaring liste shadowing the function parameter. Having liste declared in three different scopes is a recipe for disaster.
nod* liste[nrListe];
Removing those two lines seems to work.
You should probably use a better editor (I use CLion). You would have figured this out, because CLion warned me about it when I pasted your code in the editor. ;)

getting Floating point exception (core dumped). I dont know how to fix it

In the key function is gives the error. Atleast thats what gdb says. Thanks in Advance.
#include <stdio.h>
#include <stdlib.h>
#include <iostream> // for cin and cout in C++
#include <cassert> // for assert
#include <strings.h>
#include <string.h>
#include<time.h>
using namespace std;
int lcombinations=0;
int distinct=0;
linear hash function.
void linear(char *tword, int key, int n, char **lcArray)
{
int c;
while(c==0)
{
if(key==n)
{
key=0;
}
if(strlen(lcArray[key])==0)
{
lcArray[key]=tword;
c=1;
}
else
{
key++;
lcombinations++;
}
}
}
generates key for the hash function
void key(char *tword, int l, int n, char **lcArray)
{
int total=0;
int k;
for(int i=0; i<l; i++)
{
total= total+tword[i];
}
total=n%total;
k=rand()%25+66;
total=total*k;
linear(tword, total, n, lcArray);
}
int counter=0;
finds all the distinct words in the test.
void distinct_words(char *tword, char **distinct, int l, int n, char **lcArray)
{
int j;
int k=0;
if(counter==0)
{
counter++;
distinct[0]=tword;
key(tword,l,n,lcArray);
}
else
{
for(j=0; j<counter; j++)
{
if(strcmp(distinct[j],tword)!=0)
{
k++;
}
}
if(k==counter)
{
distinct[counter]=tword;
counter++;
key(tword,l, n, lcArray);
}
}
}
receives and breaks the text into words
int main()
{
srand(time(NULL));
FILE *inFile;
char word[81];
char *tword;
inFile = fopen("will.txt", "r"); // Open for reading, hence the "r"
assert( inFile); // make sure file open was OK
int i=0;
int n=65437;
int j,k;
char **distinct= (char **)malloc(sizeof(char **)*n);
char **lcArray= (char **) malloc(sizeof(char*)*n);
for(int p=0; p<n; p++)
{
lcArray[p]= (char *) malloc(sizeof(char)*81);
}
while(fscanf(inFile, "%s",word) != EOF)
{
i++;
k= strlen(word);
tword= (char *)malloc(sizeof(char)*k);
int l=0;
for(j=0; j<k; j++)
{
if(isalnum(word[j]))
{
word[j]=toupper(word[j]);
tword[l]=word[j];
l++;
}
}
printf("%s ", tword);
distinct_words(tword, distinct, l, n, lcArray);
}
}
My suspicion is that your floating point exception is generated by this line:
total=n%total;
... specifically, if total is zero, that can cause a floating point exception on many systems.
You can avoid the exception by guarding against the possibility of the modulo value being zero:
if (total != 0)
{
total=n%total;
}
else
{
printf("Hey, modulo by zero is undefined! (It's similar to divide-by-zero!)\n");
total = 0; // or something
}
By the way, one key thing you'll need to learn -- if you want to retain your sanity while programming -- is how to track down exactly where in your code a crash is occurring. You can do this using a debugger (by single-stepping through the code's execution, and/or by setting breakpoints), or you can deduce where the crash occurred by sprinkling temporary printf()'s (or similar) throughout your code so that you can see what gets printed just before the crash, and use that to narrow down the problem location. Either technique will work, and one or the other is usually necessary when merely eyeballing the code doesn't give you the answer.

Array Initialization problems: Unexpected behavior

The following program builds perfectly. However, during execution, no matter what value of degree I provide, the program takes only 2 array elements as input. I suppose there might be a problem with the redeclaration of the arrays f[] and fDash[]. In JAVA, arrays can be easily redeclared using the new keyword. Is that possible in c++ too? If not, what is the alternative?
P.S. I am using CodeBlocks 13.12 and compiler settings are standard.
#include <iostream>
#include <cmath>
using namespace std;
class Polynomial
{
public:
void input(void);
void expression(void);
void derivative(void);
double value(double var);
double der(double var);
private:
int f[];
int fDash[];
int degree;
};
void Polynomial::input()
{
cout<<"Enter degree of polynomial:\t";
cin>>degree;
f[degree+1];
fDash[degree];
for(int i=0;i<=degree;i++)
{
cout<<"Enter coefficient of x^"<<i<<":\t";
cin>>f[i];
}
for(int i=0;i<degree;i++)
{
fDash[i]=f[i+1]*(i+1);
}
}
void Polynomial::expression()
{
cout<<f[0];
for(int i=1;i<=degree;i++)
{
cout<<" + "<<f[i]<<"*x^"<<i;
}
}
void Polynomial::derivative()
{
cout<<fDash[0];
for(int i=1;i<degree;i++)
{
cout<<" + "<<fDash[i]<<"*x^"<<i;
}
}
double Polynomial::value(double var)
{
double val=0.0;
for(int i=0;i<=degree;i++)
{
val+=f[i]*pow(var,i);
}
return val;
}
double Polynomial::der(double var)
{
double val=0.0;
for(int i=0;i<degree;i++)
{
val+=fDash[i]*pow(var,i);
}
return val;
}
int main()
{
double lb,ub,step,var,accum=0.0,rms;
int counter=0;
Polynomial p;
p.input();
cout<<"\n\n\nPolynomial is:\nf(x) = ";
p.expression();
cout<<"\n\n\nDerivative is:\nf'(x) = ";
p.derivative();
cout<<"\n\n\nEnter x0,x1,Step:\t";
cin>>lb;
cin>>ub;
cin>>step;
cout<<"\n\n\n====================================";
cout<<"\n\nx\t|\tf\t|\tf'\n\n\n";
var=lb;
while(var<=ub)
{
cout<<var<<"\t|\t"<<p.value(var)<<"\t|\t"<<p.der(var)<<"\n";
accum+=pow(p.value(var),2.0);
var+=step;
counter++;
}
cout<<"\n====================================";
accum/=counter;
rms=sqrt(accum);
cout<<"\nRMS energy of f(x) = "<<rms;
return 0;
}
This does not compile on clang, it fails with "error: field has incomplete type 'int []' int f[];" and likewise for fDash.
Let's see how you declared these fields:
int f[];
int fDash[];
In C++, you can declare arrays with statically defined sizes like so:
int f[5];
int fDash[6];
If you want dynamic arrays, which you need in this case, you'd have to declare
int* f;
int* fDash;
and allocate memory for them with
f = new int[5];
You also must release that memory somewhere like so
delete [] f;
But beware - managing your own memory like this is error prone and should be avoided. You should just use std::vector instead, which is the equivalent of java.util.ArrayList:
std::vector<int> f;
std::vector<int> fDash;
And modify your input function like so:
void Polynomial::input()
{
cout<<"Enter degree of polynomial:\t";
cin>>degree;
int input;
for(int i=0;i<=degree;i++)
{
cout<<"Enter coefficient of x^"<<i<<":\t";
cin>>input;
f.push_back(input);
}
for(int i=0;i<degree;i++)
{
fDash.push_back(f[i+1]*(i+1));
}
}
You don't use arrays correctly. You need to allocate memory if you want to use array of variable length. How use arrays in c++ see this and this, or use std::vector

NFA simulator error C++

I have one big problem with my NFA simulator.
When I run the code sometimes everything goes nice, but sometimes I get this
Process terminated with status -1073741819(0xC0000005)
What do I miss out and what to do to get this work fine?
This is the code:
#include <iostream>
#include<fstream>
#include<map>
using namespace std;
ifstream fin("fisier.txt");
class NFA {
int initiala,finale,stari,tran,cuvinte;
int *f;
multimap <pair <int,int>,char>t;
public:
void stari_finale();
void tranzitii();
void rezolvare();
};
void NFA::stari_finale()
{
fin>>finale;
f=new int[finale];
for(int i=1;i<=finale;i++)
fin>>f[i];
}
void NFA::tranzitii()
{
fin>>tran;
for(int i=1;i<=tran;i++)
{
int x,y;
char c2;
fin>>x>>y>>c2;
t.insert(make_pair(make_pair(x,y),c2));
}
}
void NFA::rezolvare()
{
fin>>stari>>initiala;
fin>>cuvinte;
for(int i=1;i<=cuvinte;i++)
{
int l;
fin>>l;
char *cuv=new char[l+1];
fin.get();
fin.getline(cuv,l+1);
int *c=new int[stari],nr=1;
c[1]=initiala;
for(int j=0;j<l;j++)
{
int *c1=new int[stari];
int n=0;
for(int k=1;k<=nr;k++)
for(int z=0;z<=stari;z++)
if(t.find(make_pair(c[k],z))!=t.end())
if(t.find(make_pair(c[k],z))->second==cuv[j])
n++,c1[n]=z;
for(int k=1;k<=n;k++)
c[k]=c1[k];
nr=n;
delete c1;
}
for(int j=1;j<=nr;j++)
{for(int k=1;k<=finale;k++)
if(c[j]==f[k])
{
cout<<"Word "<<cuv<<" is accepted!\n";
nr=-1;
break;
}
if(nr==-1)
break;
}
if(nr!=-1)
cout<<"Word "<<cuv<<" isn't accepted!\n";
delete c;
delete cuv;
}
}
int main()
{
NFA test;
test.stari_finale();
test.tranzitii();
test.rezolvare();
return 0;
}
One major problem is you are not calling the right delete on your variables. If you call new you need to call delete. If you call new[] you need to use delete[]. Mixing new[] and delete calls will cause undefined behavior which is a symptom of what is happening.
Your calls to delete for c, c1 and cuv should all be delete [] variable_name
You are writing outside the array here:
void NFA::stari_finale()
{
fin>>finale;
f=new int[finale];
for(int i=1;i<=finale;i++)
fin>>f[i];
}
f has the size finale, but i will be equal to finale in the last iteration.
Use this instead:
void NFA::stari_finale()
{
fin>>finale;
f=new int[finale];
for(int i=0;i<finale;i++)
fin>>f[i];
}
or, if you really need to use the 1-based indexing:
void NFA::stari_finale()
{
fin>>finale;
f=new int[finale + 1];
for(int i=1;i<=finale;i++)
fin>>f[i];
}

C++ Object reference not set to an instance of an object

When I try to compile the following program it says "Build failed. Object reference not set to an instance of an object" . I'm kinda new to c++ so if anybody can help me it'll be great . I'm just trying out some example I saw in a book so I don't know whats wrong with this .
using namespace std;
class matrix
{
int m[3][3];
public:
void read(void);
void display(void);
friend matrix trans(matrix);
}
void matrix :: read(void)
{
cout<<"Enter the elements of the 3x3 array matrix : \n";
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cout<<"m["<<i<<"]["<<j<<"] =";
cin>>m[i][j];
}
}
}
void matrix :: display(void)
{
int i,j;
for(i=0;i<3;i++)
{
cout<<"\n";
for(j=0;j<3;j++)
{
cout<<m[i][j]<<"\t";
}
}
}
matrix trans(matrix m1)
{
matrix m2;
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
m2.m[i][j] = m1.m[j][i];
}
}
return(m2); //returning an object
}
int main()
{
matrix mat1,mat2;
mat1.read();
cout<<"\nYou entered the following matrix :";
mat1.display();
mat2 = trans(mat1);
cout<<"\nTransposed matrix :";
mat2.display();
getch();
return 0;
}
1 - Insert semi-colon after the class definition
2 - Insert the correct headers
#include <iostream>
#include <conio.h>
3 - Try getting a compiler that is a bit more descriptive with regards to errors. I did all that i mentioned and your program ran. Try it
It compiles fine after you fix your missing semi-colon (after your class declaration) and add either #include <conio.h> (Visual Studio) or #include <curses.h> (for a POSIX system) for the getch() function (which is not a standard function).