Reputation: 303
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?
Upvotes: 0
Views: 427
Reputation: 40145
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");
}
}
Upvotes: 1