Tuesday, October 22, 2013

13.10 [Cracking the Coding Interview]

Question: write a function in C which allocates a two-dimensional array

Hints: use double pointer to create a double array.

Solution 1: create a one-dimensional array of pointers, and for each array index, we create a new one-dimensional array; the drawback of this method is the memory allocated is in non-adjacent blocks.
int** mallocArray(int rows, int cols){
    int** p = (int**)malloc(rows*sizeof(int*));
    for(int i=0; i<rows; i++)
        p[i] = (int*)malloc(cols*sizeof(int)); 
    return p;
}

void freeArray(int** p, int rows){
    for(int i=0; i<rows; i++)
        free(p[i]);
    free(p);
}



Solution 2: create a consecutive block of memory for the entire two-dimensional array
int** mallocArray(int rows, int cols){
    int head = rows*sizeof(int*);
    int body = rows*cols*sizeof(int);
    int** p = (int**)malloc(head+body);
    for(int i=0; i<rows; i++)
        p[i] = (int*)(p+rows)+i*cols;
    return p;
}

void freeArray(int** p){
    free(p);
}

No comments:

Post a Comment