我正在尝试设置C风格的多维数组。它是一个301乘16的浮点值数组。我使用以下代码:
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];
}
}
但是这段代码导致崩溃,错误“释放对象的校验和不正确 - 对象可能在被释放后被修改。”
有人可能发现了什么问题吗?
答案 0 :(得分:1)
问题似乎在这里:
for (int i=0; i<16; i++) {
animationArray[i] = (float*)calloc(301, sizeof(float));
}
var i 应该是16而不是301,你刚刚分配了16个空格。
答案 1 :(得分:1)
您在for循环中关于拨号电话切换了16和301。
答案 2 :(得分:1)
您的声明中已反转16和301。所以把它改成:
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
}
另请注意,您可以按如下方式简化for循环:
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];
}
}
}