Declaring "Global" variables

First a bit of background.

Im very new to programming, having had my first college about it two weeks past now. before, knew about as much about c++ as my dog.

However, i've started a rather ambitious little pet project about a simple computer game. its called Maze, and the idea is to walk from one side to the other. basically:

Start:
OXX
XXX
XXX

victory condition:
XXX
XXX
XXO

But a bit bigger, and with impassable walls.
/backbround.

And that the problem. I want to be able to create a bigger map from inside the game without hardcoding a maximum. at this moment, I have the field information stored inside an array called map[x][y], with x and y being the dimensions of the playing field(including the border where you cant walk). However, im struggeling with the array. If i declare it as a global before the main function, than its max will be hardcoded. At the moment, de declaration looks like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int trans[10],perm[4];
//some main menu etc. 
void maap()
{
        int loop=0,count=0;
        int c=0;
        if(trans[0]==0)
        {
           int map [perm[0]+2][perm[1]+2]{};/*writemap:blanco*/
           map[perm[2]][perm[3]]=1;/*define player starting position*/
           /*define borders from here onwards*/
           for(loop=0;loop==(perm[1]+2)/*Y-axes size*/;loop++)
           {
              for(count=0;count==(perm[0]+2)/*X-axes size*/;count++)
                 {
                 if(count==0||count==(perm[1]+2)||loop==0||loop==(perm[0]+2))
                 {map[count][loop]=4;/*field value 4=side*/
                 }
          }
       }
       /*some more if's, to read the player's surroundings to enable the verification of player 
movement, and to write said movement. also, to possibly give access 
to automated/manual map-with-walls creation.*/

trans[10] is the global variable i use to send information between functions. the first digit tells the function what to do, in the above case to declare the array map[x][y] that I want so desperately to be global.
perm[4] is the array i use to store two global values, the first two remember the map size, and other two the player's location.

Here, the map[x][y] array is declared inside the map() function, because that the first time i know the size it has to be. However, i will need to access the map[x][y] array outside of this loop(but inside the function), to both read it out and to write the player's movements.

Side info: This map() function is called by a function called create(), that sets the trans[0]=0 to trigger this if.

I've tried searching this forum, since it helped me find a way to clear my screen(read: skip 100 lines). Does someone know how to make it work? Might it be possible to declare the array globally, and specify its size later? if so, how? Or am i thinking entirely the wrong way around?

As a last note, I am aware that it's considered bad pratice to use global variables, and to transfer information between functions by typing them as int function(info to transfer here). Hoever, i didn't really feel like making 10-argument functions to transfer the data.

I didn't think you guys want to see the entire +/- 100 lines of code, but if you need to, i'll post it of course.

Thanks for your time in advance.
Last edited on
I've swapped the

if(trans[0]==0)

with a switch function. This makes it a bit more readable. Will this also enable me to access the int array map[x][y] from the other cases of the switch, or will it continue not to be readable?
You need to learn how to use structs. Using arrays to store various values used for different things is a very bad idea. This is very prone to errors. You will have a hard time remembering what each position in the array is used for. Arrays should store like values (i.e. values used for the same purpose).

I can't tell from the snippet you posted what the various positions in your arrays are used for. This type of coding makes your program impossible for another person to read.

Consider the following (I have no idea if these variable names have any relation to what you're using trans for.

1
2
3
4
5
6
  struct trans_t 
  {  int what_to_do;
      int x_pos;
      int y_pos; 
      //  etc
  } trans;


As for line 9, you can't allocate arrays in C++ that way. If you want to allocate a variable length array, you need to use new.
closed account (j3Rz8vqX)
You're attempting dynamic arrays, which requires a strong sense of data management; especially if you're beyond 1 dimension.

A better alternative would be vectors, which will also require an understanding of structures and objects; but still easier than dynamic arrays.

Vector:
http://www.cplusplus.com/reference/vector/vector/
You need to learn how to use structs. Using arrays to store various values used for different things is a very bad idea. This is very prone to errors. You will have a hard time remembering what each position in the array is used for. Arrays should store like values (i.e. values used for the same purpose).


I've still to learn much, agreed. I have changed the function maap() to maap(int) so i can feed it an integer to tell it what to do. Now that i did that, i can understand why its a better solution. trans[0] has no use left now, but its still in because of the fact i'd have to change a lot of loops to incorporate the shrinking of the array.

trans[10]'s only use now is to save the player's surroundings, so that another function can verify the possibility of the move that the player wants to make. since i've got that functional after a bit of trial and a lot of error, i'll leave that for the moment.

Here's the entire function maap(int) as i've got it now:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
void maap(transfer)
{
        int loop=0;
        int c=0,s=0;
        switch(transfer)
        {
          case 0://Write a empty Map
           //Something with vectors, declaring map[x-size][y-size] Possibly:
           //map.resize(perm[0]+2)(perm[1]+2);//   ?
           map[perm[2]][perm[3]]=1;/*define player starting position*/
           /*define borders from here onwards*/
           for(loop=0;loop<=(perm[1]+2)/*Y-axes size*/;loop++)
           {
              for(c=0;c<=(perm[0]+2)/*X-axes size*/;c++)
                 {
                 if(c==0||c==(perm[0]+1)||loop==0||loop==(perm[1]+1))
                    {
                    map[c][loop]=4;/*field value 4=side*/
                    
                    }
                 }
           }
           break;
        case 1:/*readmap*/
           while(loop<=8).
           trans[1]=map[perm[2]-1][perm[3]+1];//working solution. 
           trans[2]=map[perm[2]][perm[3]+1];
           trans[3]=map[perm[2]+1][perm[3]+1];
           trans[4]=map[perm[2]-1][perm[3]];
           trans[5]=map[perm[2]][perm[3]];
           trans[6]=map[perm[2]+1][perm[3]];
           trans[7]=map[perm[2]-1][perm[3]-1];
           trans[8]=map[perm[2]][perm[3]-1];
           trans[9]=map[perm[2]+1][perm[3]-1];
           break;
        case 2:/*printmap*/
            for(loop=0;loop<(perm[1]+2);loop++)/*loop=Y-position*/
            {
               for(c=0;c<(perm[0]+2);c++)/*c=X-position*/
               {
                  s=map[c][loop];
                  switch(s)
                  {
                  case 0:/*field=empty*/
                       printf(" ");
                       break;
                  case 1:/*field=player location*/
                       printf("O");
                       break;
                  default:/*field = wall*/
                       printf("X");
                       break;
                       }
                  }
               printf("\n");//New line for next line of characters
               }
               break;
            case 3://verify victory condition
                 if((perm[0]==perm[2])&&(perm[1]==perm[3]))
                 {victory=100;}
               break;
            }
}


I think the structure as you showed would be suitable for saving the date regarding the positions of the player, but unless im understanding "structure" wrong, not for saving the walls into the array map so that i can make the program draw it.

A better alternative would be vectors, which will also require an understanding of structures and objects; but still easier than dynamic arrays.

Vector:
http://www.cplusplus.com/reference/vector/vector/


The storage has to be dynamically only in the sense that i need to determine its starting size, preferably in a way like (name)[xposition][yposition]. I will need to read locations which are by very definition not on the edges(because those are impassable), but i have to write only to the new and old location of the player, because those are the only two parts changing value(betwee 1 and 0, player present or absent).

If i understand correctly, does that mean that i could do the following:
1
2
3
4
5
6
7
8
9
10
11
12
#include <vector>//this is required for using vectors? or will stdio.h suffice? 
#include <stdio.h>
std::vector<int> map

void maap(transfer)
{
        int loop=0;
        int c=0,s=0;
        switch(transfer)
        {
          case 0:
                 map.resize(100, 0)

to resize the vector to a size of 100, filling any bonus locations with a 0?
Will this change persist upon leaving and reëntering the function? that means, will i be able to make a different call on the function to write a part of the previous stored values to my array trans[10], even if i exit the function in between?

also, did i understand that, to read/write vector elements, i would have to use
1
2
3
4
5
map.at(10);
//would give return to me the value stored there? 
map(10)=12;
//would store the value 12 there, or is there a special command? I followed you link 
//and a few more, but i could not find one... 

is there a possibility to assign vector locations like
1
2
3
 map.resize(5)(5)
//, similar to array
int map[5][5]?

this would make reading and writing back much easier..

I hope i have succeeded in clarifying my question a bit. If i am wrong in my assumptions somewhere plz let me know...
Last edited on
I really can't comment on your code any further. It's still impenetrable to the outside reader. I still have no clue what the various elements of your arrays mean. You need to use meaningful variable names instead of some obscure unnamed element of an array.

If the reason you're using arrays to hold disparate data items is to avoid using globals, I would say go ahead and use globals and as long as you make your variable names meaningful and with the understanding that globals should be avoided as your skills improve.

Line 1: You need to declare the type of transfer.
 
void maap (int transfer)


I think the structure as you showed would be suitable for saving the date [data?] regarding the positions of the player, but unless im understanding "structure" wrong, not for saving the walls into the array map so that i can make the program draw it.


A struct can be used to store whatever you want. Typically in a game, you would have an instance of a struct (or class) to represent each player, another struct to represent the playing area (board, map, world, etc). Perhaps additional structs for armor, enemies, etc. The idea is that each struct (or class) represents a different type of object and stores the information relevant to that object.

If i understand correctly, does that mean that i could do the following: [snip] to resize the vector to a size of 100, filling any bonus locations with a 0?

Yes.
Will this change persist upon leaving and reëntering the function?

You've declared map (line 3) outside of maap, so therefore it is global and yes it will persist.

1
2
map.at(10);
//would give return to me the value stored there?  


Yes, however, the usual idiom is simply:
 
  x = map[10];  // Square brackets can be used with a vector just like an array 


1
2
map(10)=12;
//would store the value 12 there 

That's not valid. Simply subscript it as you would an array.
 
  map[10] = 12;  // Note that this does not check that the subscript is inbounds 



is there a possibility to assign vector locations like
 
  map.resize(5)(5)


No. That syntax is not valid.

If you want dynamic two dimensional arrays, you can use a vector of vectors.
1
2
 
  vector<vector<int>> maap;

Last edited on
Line 1: You need to declare the type of transfer.

I've declared the transfer type along with the function itself, and it even works. I've used an limited array as a working solution, and the game works. (Yay!).

First off, thank you for your time showing a newb around. Much appreciated.

So, if I am understanding correct, I could make 2 vectors, lets call them

1
2
3
4
5
6
7
8
9
10
vector <int> mapx;//previous declaration of the "inside" vector needed?
vector <mapx<int>> mapy;


//Then I get user input about the size of the field(x=10;), I declare:

mapx.resize(x);

//And I get some more user input, (y=10;), so I say:
mapy.resize(y);

Will give me a vector-inside-a-vector with a total of 100 memory locations?

If i want to read it out, would I have to adress as following:
1
2
3
a=mapy[5[3]]
//Or something like:
mapy[5[mapx[3]]

To write the contents of x=3,y=5 to a?
A good advice I would give to you first is to use more meaningful variable names, trust me it makes others' job easier understanding your code and you'll thank yourself later.
1
2
vector <int> mapx;//previous declaration of the "inside" vector needed?
vector <mapx<int>> mapy;

No, you don't need to declare the "inside" vector, although it can help to visualize a vector of vectors by using a typedef for the inner vector.
1
2
  typedef vector<int> ROW;  //  Alias for a vector of ints
  vector<ROW> maap;          // A vector of rows 

In line 2, you're trying to use a variable (mapx) as a type to the second vector. I gave you the syntax of a vector of vectors above:
 
  vector<vector<int>> maap; 


1
2
//Then I get user input about the size of the field(x=10;), I declare:
maap.resize(x);

Yes, but understand that resizes only the outer vector. If you want to resize the inner vector then you must do that for each row.
If i want to read it out, would I have to adress as following:

Accessing the vector of vectors is simply:
 
  a = maap[5][3];  //  A simple 2 dimensional reference 











Topic archived. No new replies allowed.