Having the following code, how can I have “get” receive a map, and return the value at the specified position?
I am attempting to write a cellular automaton in C to try to wrap my head around pointers and memory allocation. Everything was fine until I decided to make “get” to obtain data instead of a direct map[x+world.w*y] as I used to.
I require this because in the future, I plan to have two maps of the same size, and use the same function to get data from them (so it’d be “get(&map2, x, y)” instead of “get(&map, x, y)”.
I do this because I was advised against using globals, so I will keep the two maps in main and send their addresses to functions to process.
This is C language, so no C++ solutions are valid.
I tried to search for this in google but all documentation is extremely technical and convoluted, and I am not sure of how this procedure is actually named… So, can anyone help me with this? How can I pass a malloc’ed array to a function and retrieve or alter data from it?
typedef struct Map {
int HP;
int type;
unsigned int flags;
} Map;
typedef struct World {
int w;
int h;
} World;
struct World world;
int tile (int x, int y) { return x + world.w * y; }
int get (/*unknown*/map , int x, int y){
int val = x + world.w * y;
return /*unknown ->?*/ type;
}
int main (){
Map* map;
world.w = 8;
world.h = 8;
int tiles = world.w * world.h;
map = (Map*)malloc(sizeof(Map) * tiles);
int i;
for(i = 0; i < tiles; i++){
map[i].type = rand()%2;
}
int x,y;
while(1){
put(0,0);
for(y = 0; y < world.h; y++){
printf("\n");
for(x = 0; x < world.w; x++){
printf("%i ", get(&map, x, y));
}
}
};
printf("\n");
return 0;
}
Instead of:
in which you pass the address of the address of the map pointer that malloc() returned, just pass the address itself:
AFAICT from your code, malloc( ) returns exactly the thing that get( ) is looking for, i.e., a pointer to someplace in memory that has room for 64 tiles. So get( ) could look something like:
int get( Map *map, int x, inty ) { int val = x + map->w * y; // map is a pointer to struct, not the struct itself return val; // get( ) returns an int, and it's in val }That might be closer to what you want.
— pete
There are a few other errors in your code, too, but this might let the compiler get off the ground.