0

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?

2
  • 1
    Did you actually allocate memory for your firstptr? Commented Aug 20, 2013 at 8:21
  • 1
    remove the * and indexes start from 0. i.e. myfirstclass firstptr; firstptr.x[3] is the last element. Commented Aug 20, 2013 at 8:22

3 Answers 3

1

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];
Sign up to request clarification or add additional context in comments.

2 Comments

I have missed the point about the allocation and I do it now, but I still got the same segmentation fault on same statement, I mean when I assign this firstptr -> x[i]; to another array in order to do some computation, I got segmentation fault. y[i]= firstptr -> x[i];
@redRose why not just use stack variables instead?
1

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.

2 Comments

@Ivan I have missed the point about the allocation and I do it now, but I still got the same segmentation fault on same statement, I mean when I assign this firstptr -> x[i]; to another array in order to do some computation, I got segmentation fault. y[i]= firstptr -> x[i];
@redRose could you show your code (how does it look with fixes)?
0

You need to allocate your class.

Before the for loop do:

firstptr = new myfirstclass;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.