Question about globals

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mikejfe
    New Member
    • Feb 2007
    • 12

    Question about globals

    Hi all. I have a question that is probably simple to answer, but I don't even know where to get started (i.e. for searching old posts, Google, etc.)

    I am writing a program that reads in a 3 dimensional array text file. Then x, y, and z coordinate values are assigned to each value of the 3d array. These four arrays (3d array, x, y, z) get used in quite a few functions of my program. So, I define them all as globals.

    My program needs to handle 3d arrays that could potentially be larger than 512x512x512, but my program doesn't know how large until the user inputs that information. I don't really want to hard code in some generic, large number when I create the arrays.

    My question is then this: Is there anyway to have these four arrays be treated as globals, but created (with the proper size) after the user enters the size of the 3d array?

    This piece of code is something I've done before, but of course sphere[i][j][k] isn't a global...
    Code:
    void LoadFile()
    {
      int ***sphere = NULL;
      sphere = new int**[userValueX];
      for (i=0; i<userValueX; i++)
        {
           sphere[i] = new int*[userValueY];
           for (j=0; j<userValueY; j++)
             {
                sphere[i][j] = new int[userValueZ];
             }
        }
    ...
    }
    Thanks in advance,
    -Michael
  • RRick
    Recognized Expert Contributor
    • Feb 2007
    • 463

    #2
    You've got the right idea for creating the arrays. Since you don't know their size, they will have to be created on the fly in your program. The way to make the variable global, is to move the definition outside of the subroutine. Move the defintion of sphere to above the sub definition.

    If you want to reference the variable outside of this file, use: extern int ***sphere.

    If you know they are only used with in the file they were defined, then preceed the definition with static. That limits their use to only this file.

    A common technique is to begin global/static variables with something unique (ie. g_) for easy identification. Since I hate '_', I capitalize the first letter of the variable.

    Comment

    Working...