Segmentation fault

Hey,
So I try to write a small thing that initializes a class which contains an array and then outputs it. However, it gives a segmentation fault on line 13. Can someone help me solve this?
Thanks for the help!!
Steffen

=================================
#include <iostream>
using namespace std;

class Array {
int number;
int *array;
public:
Array() {
number=0;
array=0;
}
void init(int amount=0) {
number=amount;
array=new int[number];
for(int i=0;i<number;i++) {
array[i]=i;
}
return;
}
void output() {
for(int i=0;i<number;i++) {
cout << array[i]<<" ";
}
cout<<endl;
return;
}
};

int main () {
//initialize
Array *a;
a->init(10);
cout<<"Output after initialization: "<<endl;
a->output();
}
=================================
The only problem is that you did not created an object of class Array before calling a->init(10);.

Here is the updated code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
using namespace std;

class Array {
int number;
int *array;
public:
Array() {
number=0;
array=0;
}
void init(int amount=0) {
number=amount;
array=new int[number];
for(int i=0;i<number;i++) {
array[i]=i;
}
return;
}
void output() {
for(int i=0;i<number;i++) {
cout << array[i]<<" ";
}
cout<<endl;
return;
}
};

int main () {
//initialize
Array *a = new Array();
a->init(10);
cout<<"Output after initialization: "<<endl;
a->output();
delete a;
return 0
}


Hope this helps !
Hey,
yeah, that helped. I feel so stupid. Thanks so much for pointing my nose to the obvious.
Steffen
Topic archived. No new replies allowed.