Boston Linux & Unix (BLU) Home | Calendar | Mail Lists | List Archives | Desktop SIG | Hardware Hacking SIG
Wiki | Flickr | PicasaWeb | Video | Maps & Directions | Installfests | Keysignings
Linux Cafe | Meeting Notes | Blog | Linux Links | Bling | About BLU

BLU Discuss list archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Quick C question



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




BLU is a member of BostonUserGroups
BLU is a member of BostonUserGroups
We also thank MIT for the use of their facilities.

Valid HTML 4.01! Valid CSS!



Boston Linux & Unix / webmaster@blu.org