Question

Currently, I have a need to store a potentially large amount of data (as doubles) in memory. I had originally created a NSObject container to store the data and added those to a NSMutableArray. However, this meant creating potentially thousands (or even hundreds of thousands) of NSObjects, the allocation of which was slowing everything down a lot. Moreover, all of those objects were eating up more memory than I'd like. This same data can be "easily" represented by a 3 dimensional c array to the effect of:

double data[fieldCount][dataAggregateCount][recordCount];
//Aggregate count is actually a static 6 at the moment, so it could be initialized:
double data[fieldCount][6][recordCount];

However, I can't really store that as an instance variable (that I know of). At present I do this:

@implementation MyClass{
    double *_data;
}

And then malloc the data:

_data = malloc(sizeof(double) * fieldCount * 6 * recordCount);

However, to access the data, I've gotta do some particularly verbose math:

double value = _data[x + (y * fieldCount) + (z * fieldCount * aggregateCount)];

What I really want is to access the data like so: _data[x][y][z] but, of course, the compiler bitterly complains about that sort of notation on a double *.

Am I being unreasonable to expect I could store a variable multidimensional c-array as an instance variable without resorting to a continuous chunk of memory and manual offset calculations?

Was it helpful?

Solution

Just allocate a three-dimensional array...

/// Allocates a 2-dimensional double array.
double **doubleArray2(int y, int z)
{
    double **a = malloc(sizeof(double *)*y);
    if(!a) {
        [NSException raise:@"no memory" format:@"haha-1"];
    }
    for(int i=0; i<y; i++)
    {
        a[i] = malloc(sizeof(double)*z);
        if(!a[i]) {
            [NSException raise:@"no memory" format:@"haha-2"];
        }
    }
    return a;
}

/// Allocates a 3-dimensional double array.
double ***doubleArray3(int x, int y, int z)
{
    double ***b = malloc(sizeof(double **)*x);
    if(!b) {
        [NSException raise:@"no memory" format:@"haha-3"];
    }
    for(int i=0; i<x; i++)
    {
        double **a = doubleArray2(y, z);
        if(!a) {
            [NSException raise:@"no memory" format:@"haha-4"];
        }
        b[i] = a;
    }
    return b;
}

have fun...

EDIT: and don't forget to deallocate the array properly when you're done ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top