I'm writing a game script, sort of in vein of 80's Rouge. My problem is that I want to send a pointer, *p_pixel_grid[8192], to another function without changing it. The other function has to recall the grid via this pointer, it supposed to have access to that part of the memory. It is necessary to redraw the grid at a later stage. Im unable to find a way, or syntax, to send it further. Any suggestions?
char grid_pointer(char grid[8192]) *//this function is just a test function to check if I can send it a pointer as an argument*
{
for (int i=0; i<=8191; i )
{
cout << grid[8192];
cout << "a";
}
}
void lvl_loader ()
{
FILE* plik;
switch(menu())
{
case 1:
{
plik = fopen("lvl 1.txt", "r");
break;
}
case 2:
{
plik = fopen("lvl 2.txt", "r");
break;
}
case 3:
{
plik = fopen("lvl 3.txt", "r");
break;
}
}
char pixel_grid[32][128];
for (int i=0; i<=31; i )
{
for (int j=0; j<=127; j )
{
pixel_grid[i][j] = fgetc(plik);
//cout << pixel_grid[i][j];
}
}fclose(plik);
char *p_pixel_grid[8192]; int pointer_counter=1;
for (int i=0; i<=31; i )
{
for (int j=0; j<=127; j )
{
p_pixel_grid[pointer_counter]=&pixel_grid[i][j];
cout << *p_pixel_grid[pointer_counter];
pointer_counter ;
}
}
grid_pointer(&*p_pixel_grid[8192]); //here, I want send this pointer to another function, possibly unchanged. The other function has to use that pointer to recall to data loaded from the .txt
}
CodePudding user response:
void grid_pointer(char ptr[][128])
{
std::cout << ptr[0][1];
std::cout << ptr[10][10];
}
int main()
{
char pixel_grid[32][128];
pixel_grid[0][1] = 'a';
pixel_grid[10][10] = 'b';
grid_pointer(pixel_grid);
}
CodePudding user response:
I'm not sure how true this declaration is here char *p_pixel_grid[8192]; because arrays are implicitly converted to pointers to their first element.
That is, it is better to make char p_pixel_grid[8192];
Passing a pointer to the array char grid_pointer(char grid[8192]) to the function; Also performed a little incorrectly. The required syntax looks like this:
void grid_pointer(char ptr[][128])
And instead of passing two parameters to the function - the pointer and the size. It is advisable to use span, it describes an object that can refer to a continuous sequence of objects with the first element of the sequence in the zero position.
#include <span>
#include <iostream>
void grid_pointer(std::span<char> grid)
{
std::cout << grid.data() << std::endl;
}
int main()
{
char p_pixel_grid[8192];
p_pixel_grid[0] = 'a';
p_pixel_grid[1] = 'b';
grid_pointer(std::span{ p_pixel_grid });
}