0

This is really stupid question to ask but I really didn't find its answer anywhere else. I am just trying to allocate memory to store pointers. It should be most easy. But annoyingly its not working (In VS2010 on Windows)...

int _tmain(int argc, _TCHAR* argv[]) { int* ints; int** intptrs; // Want to allocate space for single pointer ints = new int[10]; // Works // Want to allocate space for a integer pointer intptrs = new (int*); // Works // Want to allocate space for 10 integer pointers intptrs = new (int*)[10]; // error C2143: syntax error : missing ';' before '[' } 
4
  • do you want intptrs to be an array of 10 elements of pointers or a pointer to a pointer of 10 elemtens? Commented Jun 23, 2014 at 11:53
  • array of 10 elements of pointers Commented Jun 23, 2014 at 11:55
  • yes. but this is just i scribble to try something quick. anyways yor answer helped :) Commented Jun 23, 2014 at 11:56
  • @Andrew than moooeeeep's answer is the right thing. Commented Jun 23, 2014 at 11:56

2 Answers 2

4

The compiler error with gcc:

$ g++ test.cc test.cc: In function 'int main()': test.cc:3:23: error: array bound forbidden after parenthesized type-id test.cc:3:23: note: try removing the parentheses around the type-id 

So, you just need to remove the parentheses to remove the error:

intptrs = new int*[10]; 

As you are working with C++, I would suggest to use std::vector instead of the raw array:

#include <vector> int main() { // create 10 pointers to int std::vector<int*> intptrs(10); } 

(Note that the pointed to objects will not be deleted when the vector is destroyed. You need to do this manually, when you need to. Or use smart pointers instead of raw pointers, e.g., std::shared_ptr.)

For reference:

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

4 Comments

@mooeeeep you need to manage the memory manually before the vector is destructed.
@P0W Of course, but you'd need to do that with a raw array as well.
@mooeeeep Not when you have std::shared_ptr
@P0W Before considering smart pointers I would rather try to avoid storing pointers in the first place.
0

intptrrs is a pointer to a pointer. So this should work

*intptrs = new int[10]; 

1 Comment

That's actually wrong because intptrs is not initialized! intptrs = new int*[10]; // init the array of array *intptrs = new int[10]; // init the first array *intptrs[0] = 1; // assign 1 to the first element

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.