Quick C question

Kevin D. Clark clark_k at pannaway.com
Wed Nov 16 12:18:30 EST 2005


Anthony Gabrielson <agabriel at home.tzo.org> writes:

> 	I'm trying to some image processing in C and I won't know ahead of 
> time what the dimensions of the image are.  So I would like to do a 
> multi-dim array with a pointer so I can malloc the space and hopefully be 
> good.  The problem is that the compiler doesn't seem to agree with this 
> strategy. So does anyone have an idea of how to do something like the 
> attached example with pointers by chance?

If you wanted to ensure that the memory that comprised the 2d array
was contiguous, you could allocate the array thusly:

    int i, rows, cols, **array;

    rows = ...
    cols = ...

    array = (int **)malloc(rows * sizeof(int *));

    array[0] = (int *)malloc(rows * cols * sizeof(int));
    for(i=1; i<rows; i++)
        array[i] = array[0] + i * cols;


Ensuring the memory is contiguous might yield better cache
performance, depending on your program's memory access pattern.

Regards,

--kevin
-- 
GnuPG ID: B280F24E                     And the madness of the crowd
alumni.unh.edu!kdc                     Is an epileptic fit
                                       -- Tom Waits



More information about the Discuss mailing list