我正在尝试在ios应用程序中使用纯c编程语言实现某些功能。当方阵大小为 50(w=h=50)时,代码运行良好。如果我将矩阵的大小增加到 100,我会收到 EXC 错误访问消息。以下是我正在使用的代码:
double solutionMatrixRed[w][h];
double solutionMatrixGreen[w][h];
double solutionMatrixBlue[w][h];
double solutionMatrixAlpha[w][h];
for(int x=0;x<w;x++)
{
for(int y=0;y<h;y++)
{
//NSLog(@"x=%d y=%d",x,y);
solutionMatrixRed[x][y] = 0;
solutionMatrixGreen[x][y] = 0;
solutionMatrixBlue[x][y] = 0;
solutionMatrixAlpha[x][y] = 0;
}
}
即使w=h=100,总大小也应该是100*100*8字节,其中80KB,这是正常的。谁能说出可能出了什么问题?
您的代码在自动存储*中分配所有四个矩阵,这可能会受到限制。即使是四倍 80K 对于移动设备来说也可能太多了。
如果需要处理这么多内存,请考虑使用 malloc
从动态内存中分配它:
double (*solutionMatrixRed)[h] = malloc((sizeof *solutionMatrixRed) * w);
// allocate other matrices in the same way, then do your processing
free(solutionMatrixRed); // Do not forget to free the memory.
*通常被称为"堆栈",由在实现自动存储中经常使用的数据结构的名称。
iOS中的堆栈大小限制为512 KB。 在 w = 100 和 h = 100 时,阵列大约需要 312.5 KB。 我怀疑您超出了堆栈大小,应该尝试在堆上分配数组(使用 malloc() 分配数组)。
因为您正在尝试在堆栈上分配所有内存。虽然您应该使用动态分配 (malloc) 在堆上分配它:
double **solutionMatrixRed = malloc(h * sizeof(double *));
for(i=0; i<h; i++)
solutionMatrixRed[i] = malloc(w * sizeof(double));