objective c - C memory management with 2D arrays -
i'm starting play around c code within objective-c programs. function i'm trying write sorts of lat/long coordinates kml file clusters based on 2d arrays.
i'm using 3 2d arrays accomplish this:
nsuinteger **bucketcounts
refers number of cllocationcoordinate2d
s in cluster.
cllocationcoorindate2d **coordbuckets
array of arrays of coordinates
nsuinteger **bucketpointers
refers index in array of coordinates coordbuckets
here's code messing me up:
//initialize c arrays , indexes int n = 10; bucketcounts = (nsuinteger**)malloc(sizeof(nsuinteger*)*n); bucketpointers = (nsuinteger**)malloc(sizeof(nsuinteger*)*n); coordbuckets = (cllocationcoordinate2d **)malloc(sizeof(cllocationcoordinate2d*)*n); (int = 0; < n; i++) { bucketpointers[i] = malloc(sizeof(nsuinteger)*n); bucketcounts[i] = malloc(sizeof(nsuinteger)*n); } nsuinteger nextemptybucketindex = 0; int bucketmax = 500;
then each cllocationcoordinate2d
needs added:
//find location enter point in matrix int latindex = (int)(n * (onecoord.latitude - minlat)/(maxlat-minlat)); int lonindex = (int)(n * (onecoord.longitude - minlon)/(maxlon-minlon)); //see if necessary bucket exists yet. if not, create it. nsuinteger positioninbucket = bucketcounts[latindex][lonindex]; if (positioninbucket == 0) { coordbuckets[nextemptybucketindex] = malloc(sizeof(cllocationcoordinate2d) * bucketmax); bucketpointers[latindex][lonindex] = nextemptybucketindex; nextemptybucketindex++; } //insert point in bucket. nsuinteger bucketindex = bucketpointers[latindex][lonindex]; cllocationcoordinate2d *bucketforinsert = coordbuckets[bucketindex]; bucketforinsert[positioninbucket] = onecoord; bucketcounts[latindex][lonindex]++; positioninbucket++; //if bucket full, expand it. if (positioninbucket % bucketmax == 0) { coordbuckets[bucketindex] = realloc(coordbuckets[bucketindex], (sizeof(cllocationcoordinate2d) * (positioninbucket + bucketmax))); }
things seem going 800 coordinates, @ same point value in either bucketcounts
or bucketpointers
gets set impossibly high number, causes reference bad value , crashes program. i'm sure memory management issue, don't know c enough troubleshoot myself. helpful pointers i'm going wrong? thanks!
it seems me each entry in bucketpointers
can potentially have own "bucket", requiring unique element of coordbuckets
hold pointer bucket. entries in bucketpointers
indexed bucketpointers[latindex][lonindex]
, there can n*n
of them, allocated n
places in coordbuckets
.
i think should allocate n*n
elements in coordbuckets
.
Comments
Post a Comment