2

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;
}

3 Answers 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.

Sign up to request clarification or add additional context in comments.

3 Comments

I still get a Segmentation fault: 11 when I use p1 as a return value.
I figured it out, every time I incremented pcol+= cols, I was changing the termination part of the for loop so for (end = p1 + rows; prows < end; ++prows, pcol += cols)
Personally I prefer the index notation way, seems easier to follow.
0

try this one:

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

return p1;

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.