Reputation: 5616
I am trying to setup a C style multidimensional array. It is a 301 by 16 array of float values. I am using the following code :
float ** animationArray;
animationArray = (float **)calloc(16, sizeof(float*));
for (int i=0; i<301; i++) {
animationArray[i] = (float*)calloc(301, sizeof(float));
}
int i;
for (i=0; i<301;i++) {
NSArray * animationEntry = [Animations objectAtIndex:i];
animationArray[i][0] = [[animationEntry objectAtIndex:0]doubleValue];
animationArray[i][4] = [[animationEntry objectAtIndex:1]doubleValue];
animationArray[i][8] = [[animationEntry objectAtIndex:2]doubleValue];
animationArray[i][12] = [[animationEntry objectAtIndex:3]doubleValue];
animationArray[i][1] = [[animationEntry objectAtIndex:4]doubleValue];
animationArray[i][5] = [[animationEntry objectAtIndex:5]doubleValue];
animationArray[i][9] = [[animationEntry objectAtIndex:6]doubleValue];
animationArray[i][13] = [[animationEntry objectAtIndex:7]doubleValue];
animationArray[i][2] = [[animationEntry objectAtIndex:8]doubleValue];
animationArray[i][6] = [[animationEntry objectAtIndex:9]doubleValue];
animationArray[i][10] = [[animationEntry objectAtIndex:10]doubleValue];
animationArray[i][14] = [[animationEntry objectAtIndex:11]doubleValue];
animationArray[i][3] = [[animationEntry objectAtIndex:12]doubleValue];
animationArray[i][7] = [[animationEntry objectAtIndex:13]doubleValue];
animationArray[i][11] = [[animationEntry objectAtIndex:14]doubleValue];
animationArray[i][15] = [[animationEntry objectAtIndex:15]doubleValue];
}
}
However this code causes a crash with the error "incorrect checksum for freed object - object was probably modified after being freed."
Could anyone possibly spot what is wrong ?
Upvotes: 0
Views: 244
Reputation: 27516
You have inverted 16 and 301 in your declarations. So change it into:
float ** animationArray = (float **) calloc(301, sizeof(float*)); // Array of 301 float arrays
for (int i=0; i<301; i++) {
animationArray[i] = (float*)calloc(16, sizeof(float)); // Array of 16 floats
}
Also note that you can simplify the for loop as follows:
for (int i=0; i<301;i++) {
NSArray * animationEntry = [Animations objectAtIndex:i];
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 4; k++) {
animationArray[i][4*k+j] = [[animationEntry objectAtIndex:4*j+k]floatValue];
}
}
}
Upvotes: 1
Reputation: 554
You switched 16 and 301 in your for loop in regards to your allocation call.
Upvotes: 1
Reputation: 3346
The problem seems to be here:
for (int i=0; i<16; i++) {
animationArray[i] = (float*)calloc(301, sizeof(float));
}
The var i should be 16 instead of 301, you just allocated 16 spaces.
Upvotes: 1