2

我试图在一个函数调用中创建一个连续的内存块,该函数调用将内存的第一部分作为指向其他块的指针数组。尽管我想使用紧凑指针,但该函数使用索引表示法

Type **TwoD(size_t rows, size_t cols) 
{
    Type **p1, **prows, *pcol;

    p1 = (Type **)malloc(rows * sizeof(Type *) + rows * cols * sizeof(Type));


//  ??? something wrong here ??? I'd rather use this style if possible
//  
    //index notation works

    return prows;
}
4

3 回答 3

2

The value of prows returned is different.

prows is changed in this case:

//  for (; prows < (Type **)pcol; ++prows, pcol += cols)
//      *prows = pcol;
return prows;

while the other case, no change of prows (which is still p1):

for (unsigned ii = 0; ii < rows; ++ii)
{
   prows[ii] = pcol;
   pcol += cols;
}
return prows;

So, what you can do is at the end return p1 instead of prows.

于 2012-10-19T05:42:32.593 回答
0

试试这个:

// ======i make change here=========================
// =====================V===========================
for (; prows < (Type **)&pcol; ++prows, pcol += cols)
    *prows = pcol;

return p1;
于 2012-10-19T05:58:35.167 回答
0

我认为二维数组有点复杂。我总是使用一维数组来表示二维数组,例如:

typedef int Type; // for simplicity, assume int

Type *TwoD(size_t rows, size_t cols) {
    Type *array = (Type*)malloc(rows * cols * sizeof(Type));
    Type *p = array;
    Type counter = 0;
    for (size_t row = 0; row < rows; row++) {
        for (size_t col = 0; col < cols; col++) {
            *p++ = counter++;
        }
    }
    return array;
}

/* The array will look like this, for rows=3, cols=4:
0  1  2  3
4  5  6  7
8  9 10 11
*/

在上面的例子中,我使用了一个计数器来初始化数组,但是你可以做不同的事情。

于 2012-10-19T06:00:13.753 回答