数组
#include<iostream> #include<cstdio> #include<cstdlib> using std::cin; using std::cout; typedef int type; typedef struct array { type *base;//基址 int index[3];//数组每维大小 int count[3];//用于计算,储存每维的元素个数,例:每面,每行,每列的元素个数 }; //初始化三维数组,并返回是否成功 int init(array*a, int x, int y,int z) { if (x < 0 || y < 0 || z < 0)return 0; a->index[0] = x; a->index[1] = y; a->index[2] = z; a->base = new int[sizeof(type)*x*y*z]; if (!a->base)return 0; a->count[0] = y*z; a->count[1] = z; a->count[2] = 1; return 1; } //通过num指针返回x,y,z的数组元素值,并通过函数返回是否访问成功 int Value(array*a, int x, int y, int z, int *num) { if (x < 0 || x >= a->index[0] || y < 0 || y >= a->index[1] || z < 0 || z >= a->index[2]) return -1; int off = x*a->count[0] + y*a->count[1] + z*a->count[2]; *num = *(a->base + off); return 1; } //返回x,y,z位置的数组元素的值,失败返回-1.. int value(array*a, int x, int y, int z) { if (x < 0 || x >= a->index[0] || y < 0 || y >= a->index[1] || z < 0 || z >= a->index[2]) return -1; int off = x*a->count[0] + y*a->count[1] + z*a->count[2]; //*num = *(a->base + off); return *(a->base+off); } //将num赋值给x,y,z位置的元素,通过函数返回是否成功 int assign(array*a, int x, int y, int z, type num) { if (x < 0 || x >= a->index[0] || y < 0 || y >= a->index[1] || z < 0 || z >= a->index[2]) return 0; int off = x*a->count[0] + y*a->count[1] + z*a->count[2]; *(a->base + off) = num; return 1; }
//一些乱乱的函数 //填充整个数组,用于测试 void Fill(array*a) { int i, j, k, c = 0; for (i = 0; i < a->index[0]; i++) for (j = 0; j <a->index[1]; j++) for (k = 0; k <a->index[2]; k++, c++) assign(a, i, j, k, c); } //打印整个数组,用于测试 void Out(array*a) { int i, j, k; for (i = 0; i < a->index[0]; i++) { for (j = 0; j < a->index[1]; j++) { for (k = 0; k < a->index[2]; k++) { printf("(%d,%d,%d):%d", i, j, k, value(a, i, j, k)); } printf("\n"); } printf("\n\n"); } } int main() { int i, j, k, c = 0; array a, *p = &a; init(p, 3, 3, 3); Fill(p); Out(p); }
版权声明:本文为博主原创文章,未经博主允许不得转载。