Hey Guys n Gals Im a newbie here and I am having trouble with putting input into a two dimensional array.
What I have to do is put the users numbers (integers not doubles) into a matrix add them, subtract them and multiply.
I have most of my code written it is just when i try assign the input into the array it compiles fine i just keep on getting a segmentation fault when i run the program, which I assume means when i am trying to input the information into the array it gives me this fault...I am not sure what I can do to make this work!
Currently I am just trying in a double for loop
cin >> c;
A[j]=c;

I don't know if this is the right method it is just the only way I have read in my class notes etc! Any Help would be greatly appreciated!

Seg faults can have all sorts of causes. Most likely i and j are not valid indexes for the array. It's impossible to tell though without seeing more code.

Okay sorry :D So thjs is a matrix class that i have written I know that I can get into the function fine and I can also get into the loop and everything fine, just a matter when i try to do the A[j]= c it doesnt work, however if i comment it out and just cout a random sentance it goes into the loop fine and prints to the screen the proper amount of time.. Hopefully that helps out a little?!

Matrix::Matrix(int m, int n)
{
int = c;
row =m;
col =n;
for (int i =0; i< row; i++)
for(int j =0; j<col; j++)
{
cout << "enter and int: " ;
cin >> c;
A[j] = c;
}
}

int = c;

I assume this is

int c;

Change this line:

A[i][j] = c;

to this:

A[0][0] = c;

See if it works(this is purely for debugging. You'll want to change it back).

It it still crashes, then the problem is that the A[][] matrix isn't defined correctly. If it doesn't crash, then that means that i and j are bad indexes, so make sure the the A[][] array is declared up to at least A[m][n].

Yeah, your code looks like a constructor but you don't assign memory for the array at any point, so trying to access elements to change their values will seg. fault. Unless you have declared A as a 2D array on the stack (which would not be a good idea, since you wouldn't be able to resize it or make it anything but quite small), then I'd expect to see something like:

/* Declarations */
class Matrix{
public:
    Matrix(unsigned rows, unsigned cols);

    /* other public member functions */

private:
    int *A;
    unsigned rows;
    unsigned cols;
}

/* Implementation */
Matrix::Matrix(unsigned m, unsigned n){
    A = new int[n*m];
    rows = m;
    cols = n;
    
    /* The bit to get the values here ... */
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.