i love stackoverflow
i love stackoverflow

Reputation: 1685

Arrays inside structures

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!

Upvotes: 0

Views: 100

Answers (1)

juanchopanza
juanchopanza

Reputation: 227578

Because class C holds a pointer to an A, which has not been initialized. So there is no a->data to initialize at that stage.

As an aside, your struct A doesn't hold a "pointer to an array", it holds a pointer to an int. It doesn't necessarily have to be initialized to point to a dynamically allocated array:

int n = 42;
A a;
a.data = &n;

Also, your declaration of A is somewhat unusual in C++, and inconsistent with that of class C. Usually this form is used:

struct A {
  int* data;
};

Upvotes: 7

Related Questions