Reputation: 3467
I can run this
int a = 5;
auto foo = new int [a][4][4];
But when I try this:
int a = 5;
int * foo[4][4];
foo = new int [a][4][4];
I get the error
error: incompatible types in assignment of ‘int (*)[4][4]’ to ‘int* [4][4]’
What type do I have to specify for foo
?
Edit: The goal is to have one single chunk of memory, not an array of pointers.
Upvotes: 2
Views: 81
Reputation: 1226
As @john correctly identified:
You're confused between a 2D array of pointers (that's what you wrote) and a pointer to a 2D array (that's what you want).
So what's the difference between pointer to an array and array of pointers. The correct syntax to define a pointer to an array (what you tried to do):
data_type (*var_name)[array_size];
But this defines an array of pointers (what you actually did):
data_type *var_name[array_size];
@OP in your own answer you already found out what the correct type should be – a pointer to an array int (*foo)[4][4]
, but I thought a little more explanation is also helpful.
Upvotes: 2
Reputation: 3467
The error message is a little confusing because it does not state the variable name.
This works:
int a = 5;
int (*foo)[4][4];
foo = new int [a][4][4];
Upvotes: 3