I’m sorry if I didn’t pick a descriptive or concise name. A lot of questions sound similar, but I haven’t been able to find what I’m looking for. What I want to do is store a 2D array of pointers somewhere and assign a variable in some object to that array to be able to access it.
Here’s some example code that has the same compile error I’m getting with a bigger project.
#include <iostream>
using namespace std;
struct X{
float n, * b[8][8];
X(){
n = 1;
b[1][5] = &n;
cout << *(b[1][5]) << endl;
}
void Set(float * c[8][8]){
b = c;
cout << *(b[1][5]) << endl;
}
};
main(){
float m, * a[8][8];
m = 2;
a[1][5] = &m;
X obj;
obj.Set(a);
}
What I want to happen in this code is that an X object starts with its own 2D array, whose value pointed to by b[1][5] should be printed as “1”. Then the main method’s 2D array, a, is passed to the object’s Set() method and assigned to its array variable. The value pointed to by b[1][5] should then be printed as “2”.
However, I can’t figure out what type the Set() parameter, c, should be. I get
error: incompatible types in assignment of ‘float* (*)[8]’ to ‘float* [8][8]’
when I try to compile. As for why I want to do this, I’m trying to use an array of pointers to objects, not floats, but it’s the same error.
Try this:
Here,
Xstores a pointer to a 1D array, which we are treating as a pointer to the first element of a 2D array – i.e. as just a 2D array.In
X‘s constructor,Xallocates its own array withnewand sets its pointer to point to that. When callingSet(),Xdeletes its own array, and sets its pointer to point to the array provided by the caller.The only thing to watch out for is, if you call
Set()again, that array will in turn be deleted (which will blow up if that array is a stack array, like in this case). So, it might be advisable to separate the line that doesdelete[] binto its own member function, and call it only when necessary.