Posts Tagged ‘DS’
动态二维数组实现 C
July 1, 2010
Leave a comment
“定义一个二维指针的空间分配和释放 int **ptr”
1. 调用malloc 函数 次数: ( rows + 1)
int** New2DPointer(int m, int n) { if (m > 0 && n > 0) { typedef int * INT_POINTER; int **ptr = NULL; try { ptr = new INT_POINTER[m]; for (int i = 0; i != m; ++i) { ptr[i] = new int[n]; } } catch (bad_alloc e) { std::cout << “Error allocating memory.” << std::endl; } return ptr; } else { std::cout << “invalided input parameters\n”; } } void Delete2DPointer(int **p, int m) { for (int i = 0; i != m; ++i) { delete [] (p[m]); } }
调用malloc 函数 次数: ( 1 + 1)
int **array2d_new(size_t rows, size_t cols) { int **array2d, **end, **cur; int *array; cur = array2d = malloc(rows * sizeof(int *)); if (!array2d) return NULL; array = malloc(rows * cols * sizeof(int)); if (!array) { free(array2d); return NULL; } end = array2d + rows; while (cur != end) { *cur = array; array += cols; cur++; } //print_2d_array(m, rows, cols); return array2d; }
调用malloc 函数次数: ( 1 + 1), 看上去更牛B些
void ** array2d(size_t rows, size_t cols, size_t value_size) { size_t index_size = sizeof(void *) * rows; size_t store_size = value_size * rows * cols; char * a = (char*)malloc(index_size + store_size); if(!a) return NULL; memset(a + index_size, 0, store_size); for(size_t i = 0; i < rows; ++i) ((void **)a)[i] = a + index_size + i * cols * value_size; return (void **)a; } int printf(const char *, ...); int main() { int ** a = (int **)array2d(5, 5, sizeof(int)); assert(a); for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++) a[i][j] = i*j; //a[4][3] = 42; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) printf("%i\t", a[i][j]); printf("\n"); } free(a); return 0; }
Categories: algorithm & DS
C, DS