Two dimensional array allocation
i have following code for allocation tw开发者_如何学Pythono dimensional array
#include <iostream>
using namespace std;
int **malloc2d(int r,int c){
int **t=new int*[r];
for (int i=0;i<r;i++)
t[i]=new int[c];
for (int i=0;i<r;i++){
for (int j=0;j<c;j++){
t[i][j]=i+j;
}
}
return t;
}
int main(){
int m=10;
int n=10;
int **a=malloc2d(m,n);
for (int i=0;i<m;i++){
for (int j=0;j<n;j++){
cout<<a[i][j]<< " ";
cout<< " \n";
}
cout<< " \n";
}
return 0;
}
it works but my question is: how good is this code according to performance efficienty or according to code speed? thanks
With an int **
you have lots of pointers to tiny (4 byte) memory spaces which is inefficient due to malloc overhead (every malloc implementation has an overhead, the minimum normally is sizeof(void*)
AFAIK which in your case would mean there's at least a 100% overhead for all "cells").
As an alternative, you could use a one-dimensional array and calculate the indexes yourself like this: index = (row * num_columns) + column
. You would lose the nice a[row][column]
notation, though. Still, it should be faster to access as well because in your (clean) solution there have to be two pointer dereferences (memory operations) while in the way I suggest you only have one. It would look something like this:
#include <iostream>
using namespace std;
inline int a_index(int row, int column, int column_size) {
return((row * column_size) + column);
}
int *malloc2d(int r,int c) {
int *t=new int[r * c];
for (int i=0;i<r;i++){
for (int j=0;j<c;j++){
t[a_index(i,j,c)]=i+j;
}
}
return t;
}
int main(){
int m=10;
int n=10;
int *a=malloc2d(m, n);
for (int i=0;i<m;i++){
for (int j=0;j<n;j++){
cout<<a[a_index(i,j,n)]<< " ";
cout<< " \n";
}
cout<< " \n";
}
return 0;
}
I assume you plan to add delete[]
, or the program will terminate before leakage matters.
Anyway, it won't be very efficient.
First, the array will be composed of non-contiguous blocks of memory. That makes it harder for the machine's memory subsystem to handle.
Second, some extra space is being wasted to hold the array of pointers.
Just do it the old fashioned way:
int *a = new int[ r * c ];
or with vector
std::vector<int> a( r * c );
and compute indexes as ever:
cout << a[ i * c + j ] << ' ';
However, since you are looping over the entire array, you could ignore the two-dimensionality except for formatting:
for ( int i = 0; i < r * c; ++ i ) {
cout << a[ i ] << ' ';
if ( i % c == c-1 ) cout << '\n';
}
If you don't delete the memory that you have allocated by using new, then you will leak memory.
精彩评论