redRose
redRose

Reputation: 83

Segmentation fault when trying to access an array inside pointer

I got segmentation fault when I start running my project.

I have declared 2 different classes

Class myfirstclass {
int x[4];
};

In the second class

I access the array “x[4]” using the following

myfirstclass  * firstptr;
firstptr -> x[4];

Now when I assigned the “firstptr -> x[4];” to an array to do some computations I got a segmentation fault?

int y[4];
for (int i=0; i<4;i++){
  y[i]= firstptr -> x[i]; -> "This statement what caused the segmentation fault."
}

Can you help me fixing this error, please?

Upvotes: 0

Views: 1062

Answers (3)

Ivan
Ivan

Reputation: 649

You have to create object before usage. Something like that:

myfirstclass  * firstptr = new myfirstclass();

Or you should discard using dynamically allocated object

myfirstclass  firstptr;
int y[4];
for (int i=0; i<4;i++){
  y[i]= firstptr.x[i]; -> "This statement what caused the segmentation fault."
}

In order to access x you should make it public:

class myfirstclass {
public:
int x[4];
};

Actually, making data field bublic is not recommended.

Upvotes: 1

doctorlove
doctorlove

Reputation: 19242

If you just do this

myfirstclass  * firstptr;
firstptr -> x[4];

You haven't initialised firstptr. You would need to do something like

myfirstclass  * firstptr = new myfirstclass();

Don't forget to delete firstptr somewhere.
Or just use the stack

myfirstclass  first;

Next, you are using

firstptr -> x[4];

Since you have int x[4]; you have 4 items, so can access x[0], x[1], x[2] and x[3]. There is no x[4]

Note - if you use the stack instead just use . instead of ->

first.x[i];

Upvotes: 1

Huygens
Huygens

Reputation: 647

You need to allocate your class.

Before the for loop do:

firstptr = new myfirstclass;

Upvotes: 0

Related Questions