1

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.

2
  • n is zero? That won't work correctly. Also regardless of the size of n you want your loop to terminate on i < n as your array is index from 0 to n-1. Commented Nov 19, 2014 at 18:05
  • Where the ... do you see a global static array? Commented Nov 19, 2014 at 18:23

2 Answers 2

4

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;

Sign up to request clarification or add additional context in comments.

2 Comments

missing if(arr) delete [] arr; before new allocation.
@SHR, yeah, the OP should check this :)
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.