I tried to compile the following code using g++. Could anyone help point out what is wrong here. Thanks a lot. Happy holidays.
==== code ====
#include <iostream>
using namespace std;
#define NUM 10
struct TypeA {
int aa;
};
int main() {
TypeA *c = NULL;
c = new TypeA;
c = NULL;
cout << c << endl;
TypeA *d[NUM];
for (int i = 0; i < NUM; i++) {
d[i] = new TypeA[NUM];
}
for (int i = 0; i < NUM; i++) {
for (int j = 0; j < NUM; j++) {
d[i][j] = NULL;
}
}
return 0;
}
==== compiling result
-bash-2.05b$ g++ main1.cc
main1.cc: In function `int main()':
main1.cc:26: error: no match for 'operator=' in '*(d[i] + (+(j * 4))) = 0'
main1.cc:7: error: candidates are: TypeA& TypeA::operator=(const TypeA&)
My purpose is as follows.
I want to create a 2-D pointer array in which each element is a pointer pointing to .... To make the program safer, I would like to make all pointers in my 2-D pointer array point to NULL. And then I will check if an element points to NULL before trying to use it.
Here I come up with a simpler program to reflect the problem. I update my first post. Thanks,
This way is cheaper memory-wise, and probably computationally, since there's only one level of indirection. If you really want to do it like that, it's just a matter of adding more indirection.
I'm going to obviate the initialization to zero to save me some typing:
1 2 3 4 5
T ***a=new T **[w];
for (int b=0;b<w;b++)
a[b]=new T *[h];
//...
a[x][y]=new T;
Hi, you are so helpful. THANKS A LOT. I agree! I implemented your code as follows. I thought they did the same thing. Please point out if you find something incorrect.
======
1 2 3 4 5 6 7 8 9 10 11 12
TypeA **e[NUM];
for (int i = 0; i < NUM; i++) {
e[i] = new TypeA *[NUM];
}
for (int i = 0; i < NUM; i++) {
for (int j = 0; j < NUM; j++) {
e[i][j] = NULL;
cout << e[i][j] << endl;
}
}
=======
BTW, the reason for e[i][j] is to ease the operations.
None of the asterisks in my snippet are optional. You have to be very careful about that.
Is NUM a small (let's say <20) constant? If so, you could do T *array[NUM][NUM];
If it's not a small constant, you can still do it like that, but if the object is not created with new, you could overflow the stack.
Depends, like I said, on how you're going to allocate the object, and whether NUM is a small constant. If you're absolutely sure you're always going to allocate TypeA dynamically (e.g. TypeA *obj=new TypeA;), then yes, and the value of NUM doesn't matter for the most part.