简体   繁体   中英

C: Reading int** from void*

so im trying to define a generic ADT. i have a struct that looks like this:

struct grid_type{
    void* table;
    int startX, startY, endX, endY, xDim, yDim;
};

as you can see i have a void pointer which should be able to store various data types. for this instance im trying to point to an int** (two dimensional array) which is returned by this function:

int** CreateInt(int xDim, int yDim){
    int** table = NULL;
    int i, j;
    table = (int**)malloc(xDim*sizeof(int*));
    if (table == NULL){
        puts("failed malloc");
        exit(1);
    }
    for (i = 0; i < xDim; i++){
        table[i] = (int*)malloc(yDim*sizeof(int));
        if (table[i] == NULL){
            puts("failed malloc");
            exit(1);
        }
        for (j = 0; j < yDim; j++){
            table[i][j] = 1;
        }
    }
    return table;
}

pretty basic function. so what im failing to do is reading from this array later, can't seem to access any data. this is how im trying:

void PrintInt(grid* grid){
    int i, j, add = 0;
    for (i = 0; i < grid->xDim; i++){
        for (j = 0; j < grid->yDim; j++){
            add = i*(grid->xDim-1) + j;
            printf("%d   ", *((int*)grid->table+add)); <--- PROBLEM
        }
        printf("\n");
    }
}

and this is how it all happens in the main:

grid1 = CreateGrid((*CreateInt), xDim, yDim, startX, startY, endX, endY);
PrintInt(grid1);

what im getting is 100% jibrish, any ideas?

void PrintInt(grid* grid){
    int i, j;
    int **table = grid->table;
    for (i = 0; i < grid->xDim; i++){
        for (j = 0; j < grid->yDim; j++){
            printf("%d   ", table[i][j]);
        }
        printf("\n");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM