[ create a new paste ] login | about

Link: http://codepad.org/nDy8z2iG    [ raw code | fork ]

joel_f - C++, pasted on Jul 5:
template<class T> static inline T** alloc( size_t h, size_t w )
{
  typedef T* ptr_type;
  ptr_type* m;
  m    = new ptr_type[h];
  m[0] = new T[h*w];
  for(size_t i=1;i<h;i++) m[i]=m[i-1]+w;
  return m;
}

template<class T> static inline T** share( T* data, size_t h, size_t w )
{
  typedef T* ptr_type;
  ptr_type* m;
  m    = new ptr_type[h];
  m[0] = data;
  for(size_t i=1;i<h;i++) m[i]=m[i-1]+w;
  return m;
}

template<class T> static inline void release( T** ptr, bool is_shared = false )
{
  if(ptr && !is_shared) delete[] ptr[0];
  if(ptr) delete[] ptr;
}

int main()
{
  float** tab;
  int width  = 5;
  int height = 3;
  tab = alloc<float>(height, width); // column first

  for(int r = 0;r<height;++r)
   for(int c = 0;c<width;++c)
    tab[r][c] = 1./(1+r+c);

  release(tab);
}


Output:
No errors or program output.


Create a new paste based on this one


Comments: