1

I am new to C/C++ and I had a question about dynamically allocating arrays. Can you not make a global dynamically allocated array? What if I wanted arr to be used by multiple functions? Would I have to pass arr to every function? Basically I guess I am still confused on the concept of dynamically allocated arrays and how I could create an array that can be used by a few functions.

The following produces : error: ‘arr’ does not name a type, but I am not sure exactly why.

#include <iostream>      

using namespace std;

int * arr = NULL;
arr = new int [10];

int main() {
   arr[0] = 1;
   return 0;
}
8
  • @jrok: That's not how C syntax works Commented Feb 6, 2013 at 22:05
  • @Eric You're absolutely correct. C doesn't have new :) Commented Feb 6, 2013 at 22:06
  • 1
    "Global" and "dynamically allocated" are really mutually exclusive. Global variables have static storage, and dynamically allocated ones have dynamic storage. You can of course have a global pointer to a dynamically allocated object. Commented Feb 6, 2013 at 22:11
  • 1
    Oh :) well that's a typo, nit-pickers. Thanks for pointing it out, anyway :) Commented Feb 6, 2013 at 22:17
  • 1
    @jrok: nitpicking is awesome :P Commented Feb 6, 2013 at 22:22

4 Answers 4

3

That's invalid for the same reason that this is invalid

#include <iostream>      

using namespace std;

int a = 0;
a = 2;

int main() {

}

You can't run statements outside of a function, only initializers. As a result, this works:

#include <iostream>      

using namespace std;

int *arr = new int[10];

int main() {
   arr[0] = 1;
   return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

3

You don't even have to make the array dynamic, you can just put the array in static memory outside main, and it will live as long as the program.

#include <iostream>     

int arr[10];

int main() {
   arr[0] = 1;
   return 0;
}

Comments

1
int* arr = new int[10];

or (since you are allocate a constant size array):

int arr[10];

Comments

1

You can't have "code" outside of a function. You need to put the call to new inside a function - you only have one in your code: main, but as long as it is a function that is executed before you access the array, it's fine.

You can also, as the comment says, do int *arr = new int[10]; - as long as it's part of the initialization, and not on a separate line.

1 Comment

int *arr = new int[10] is perfectly valid in global scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.