I am a Fortran user and do not know C++ well enough. I need to make some additions into an existing C++ code. I need to create a 2d matrix (say A) of type double whose size (say
To allocate dynamically a construction similar to 2D array use the following template.
#include
int main()
{
int m, n;
std::cout << "Enter the number of rows: ";
std::cin >> m;
std::cout << "Enter the number of columns: ";
std::cin >> n;
double **a = new double * [m];
for ( int i = 0; i < m; i++ ) a[i] = new double[n]();
//...
for ( int i = 0; i < m; i++ ) delete []a[i];
delete []a;
}
Also you can use class std::vector
instead of the manually allocated pointers.
#include
#include
int main()
{
int m, n;
std::cout << "Enter the number of rows: ";
std::cin >> m;
std::cout << "Enter the number of columns: ";
std::cin >> n;
std::vector> v( m, std::vector( n ) );
//...
}
As for this code snippet
int * x;
x = new int [10];
then x
has type int *
and x[0]
has type int
. So if the size of the pointer is equal to 4 and the size of an object of type int is equal also to 4 then sizeof( x ) / sizeof( x[0] )
will yields 1. Pointers do not keep the information whether they point to only a single object or the first object pf some sequence of objects.