-6

To solve a problem I need a 2D array which should be accessed by other functions. I feel it problematic to pass the pointer and then using the pointer in other functions. As the dimension of the array is input dependent so I don't want to declare a huge 2D global array.
So I want to declare a 2D array in main as a global array and access it from other functions.

naimul64
  • 133
  • 3
  • 17
  • 1
    passing a pointer or reference is a much better way to approach this. If you want an actual global variable, it would have to be defined *outside* the main function. That said, don't do it! – Nicolas Holthaus Sep 23 '15 at 18:54
  • 7
    "I feel it problematic to pass the pointer and then using the pointer in other functions." Please explain why you think so. – Sergey Kalinichenko Sep 23 '15 at 18:55
  • 1
    And also put some concise sample code in your post, to better explain what you actually want to do, please. – πάντα ῥεῖ Sep 23 '15 at 19:10
  • 1
    The problem here is that you don't want to just pass the array. There's no reason to not pass the array. – Puppy Sep 23 '15 at 19:14

3 Answers3

4

In C++, if you need an array of variable size, 99% of the time, you should be using a std::vector.

I agree that you should be passing a pointer. Let's suppose you have some very good reason for not doing this. Then, declare the std::vector at global scope and give it the desired size inside main.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Brian Bi
  • 111,498
  • 10
  • 176
  • 312
2

As from your question title

Is it possible to declare a global variable inside main function in c++? If possible how?

No, it's not possible to declare global variables inside the main() , or any other functions' scope. Global variables must be declared outside of any functions scope.

As you mentioned an array with variable size depending on runtime input, the arrays size can't be determined at compile time.

Even if your compiler supports VLA's, these can't be used at global scope.

As @Brian already pointed out, you need some dynamic memory allocation at runtime like it's provided by e.g. a std::vector:

 std::vector<int> myArray;

 void initArray() {
      int arraySize;
      std::cout << "Enter array size: "; 
      std::cout.flush();
      if(std::cin >> arraySize) {
          myArray.resize(arraySize);
      }
 }
Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
0

You can always use pointer to std::vector for this. Here is an example code,

#include <iostream>
#include <vector>
using namespace std;

vector<int>* v;

int main(){
int n;
cin >> n;
v = new vector<int>(n);
// now you can simply pass the vector to any function
}
Selie
  • 43
  • 6