Reputation: 495
I'm trying to create a continuous block of memory in one function call that has the first part of the memory as pointer arrays to the other blocks. The function works with an index notation though I'd like to use compact pointer
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;
}
Upvotes: 2
Views: 106
Reputation: 1003
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.
Upvotes: 2
Reputation: 40723
I think two-dimensional array is a little complicated. I always use a single-dimensional array to represent a 2D one, for example:
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
*/
In the above example, I use a counter to initialize the array, but you can do differently.
Upvotes: 0
Reputation: 303
try this one:
// ======i make change here=========================
// =====================V===========================
for (; prows < (Type **)&pcol; ++prows, pcol += cols)
*prows = pcol;
return p1;
Upvotes: 0