help on arrays

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • faybesp
    New Member
    • Jan 2009
    • 1

    help on arrays

    i am getting difficulties understanding the following piece of code:
    (assuming T being any variable type)
    *M = new T* [xdim]; **M = new T [xdim*ydim];
    if (*M==NULL || **M==NULL) return false;
    for(sint i=1; i < xdim; i++)
    (*M)[i] = (*M)[i-1] + ydim;

    Thanks in advance
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Code:
    *M = new T* [xdim];
    This allocates an array of T* that has xdim elements. The new operator returns
    a pointer to element 0 of the array so *M has to be a T** making
    M itself a T***.
    Code:
     **M = new T [xdim*ydim];
    Again the new operator returns the address of an array of T that has
    xdim*ydim elements. Since M is a ***T from the first example, then **M
    is a T* and the new operator is returning a T*.
    Also, the variable M is used for two arrays resulting in a horrible memory corruption.
    Code:
    if (*M==NULL || **M==NULL) return false;
    This code is baloney:
    a) there is no NULL in C++. NULL is a C macro for zero.
    b) the new operator never returns zero when it runs out of memory. Instead, it throws a bad_alloc exception.
    c) you can't have two arrays at the same address.

    Code:
    for(sint i=1; i < xdim; i++)
    (*M)[i] = (*M)[i-1] + ydim;
    Here sint has to be a typedef of int. Why??
    The loop is garbage since the *M array has only xdim elements.

    Comment

    Working...