I am trying to write a function to allocate an upper triangular matrix. it should return a pointer to the first element of the allocated array. I also need to use dynamic allocation to ensure that the exact amount of required memory is allocated but I am not quite sure how to do that... Any tips or advice would be greatly appreciated! I am a noob to c++.. Anyway here is my code if that helps!
#include <iostream>
using namespace std;
int main ()
{
int a[3][3],i,j; //creating two dimensional array
int d;
int * p;
cout<<"Please Enter the 9 elements of matrix (with spaces): ";
for(i=0;i<3;i++)
for(j=0;j<3;j++)
cin>>d,&a[i][j];
cout<<"\nThe matrix is\n ";
for(i=0;i<3;i++)
{
cout<<"\n";
for(j=0;j<3;j++)
cout<<d,a[i][j];
}
cout<<"\nSetting zero in upper triangular matrix\n";
for(i=0;i<3;i++){
cout<<"\n";
for(j=0;j<3;j++)
if(j>=i)
cout<<d,a[i][j];
else
cout<<0;
}
return 0;
}
cin>>d,&a[i][j]
does. It surely doesn't do what you think it does - David Heffernan 2012-04-03 20:22
cin>>d,&a[i][j];
is a funny construct - you read into d and then get address of a[i][j]
promptly discarding it - Anycorn 2012-04-03 20:23
As per oli's comment I think you are looking to do
cin >> d; a[i][j] = d;
vs
cin>>d,&a[i][j];
I suggest reading something like .... http://www.cplusplus.com/doc/tutorial/basic_io/
theres your first issue
dynamic allocation is done through code like new and malloc try reading...
http://www.cplusplus.com/doc/tutorial/dynamic/
as for how to store your upper matrix... I would recommend just using a normal 2d matrix chances are it will work better with most matrix libraries out there.
Good luck with your homework.
Normally when allocating an upper triangular matrix of size N you allocate N + N-1 ... + 1 (look up sum of integers) elements, and then you need to either create access mechanisms (likely what is intended here) so that when you want element M(i,j) you get the element in row i, column j, despite the fact that (nearly) half the elements are missing; or do that manually when using the matrix in whatever matrix manipulation code uses it.
You treat the one dimensional array as if the first N elements are the first row, the next N-1 elements are the (right N-1 elements of the) second row, and so on.
Because this question looks and smells like homework, I think that's about as much hint as appropriate.
cin>>d,&a[i][j]
to do.. - Oliver Charlesworth 2012-04-03 20:14