So I created a struct whose only element is a pointer to an array. When I initialize this array, I get a segmentation fault. Can you tell me why?
Here is the code:
typedef struct {
int *data;
} A;
/* Class definition */
class C {
A* a;
public:
C(void);
};
/* Constructor */
C::C(void) {
a->data = new int[10];
}
int main(void) {
C();
}
Thank you!
Because class
Cholds a pointer to anA, which has not been initialized. So there is noa->datato initialize at that stage.As an aside, your struct
Adoesn’t hold a “pointer to an array”, it holds a pointer to anint. It doesn’t necessarily have to be initialized to point to a dynamically allocated array:Also, your declaration of
Ais somewhat unusual in C++, and inconsistent with that ofclass C. Usually this form is used: