MuchaZ
MuchaZ

Reputation: 421

A global static array in C++

I've got something like this:

static int n = 0; // global static int
int *arr = new int[n]; // global int*

int randToArray(int arr[], int min, int max) {
    srand(time(NULL));
    for(int i = 0; i <= n; i++) {
        arr[i] = (rand() % max + min);  
    }           
}

void printArray() {
    if(n) {
        for(int i = 0; i < n; i++)
        cout << arr[i] << endl; 
    } else
        cout << "The array hasn't been drawed yet.";        
}

And then in the main function I have a menu with a switch and options for getting random numbers and printing the array:

switch(option) {
case 1:
    cout << "Set the size of the array: ";
    cin >> n;
    randToArray(arr, 1, 99);
    break;
case 2:
    printArray();
    wait();
    break;
}

I need my array to be available globally in order to use in several other functions.

Everything works except one thing: when I want to print the array I get working properly only 8 first elements. Then the terminal shows up some very large numbers.

Upvotes: 1

Views: 2296

Answers (2)

Deduplicator
Deduplicator

Reputation: 45654

static is a much overloaded keyword.
The way you use it, it means translation-unit-local.

Also, you don't have any global array in your code, only a pointer initialized to point to the beginning of an allocation of 0 ints.
That allocation won't be changed if you later change n.

Upvotes: 0

vsoftco
vsoftco

Reputation: 56547

That's because you use

static int n = 0;

then allocate memory for zero elements.

Change the line static int n = 256; for example, to allocate memory for 256 elements.

Or, if you read n after, allocate the memory AFTER you have read n. That is, declare the array globally first (technically a pointer), as int *arr;, then

arr = new int[n];

after cin >> n;

Upvotes: 4

Related Questions