variable-sized object `val' may not be initialized

I have problem compiling the following 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
class sample
{
public:
    static const unsigned int d = 5;
    static const unsigned long int M = 10000000;
    double** val;
	sample();
	~sample();
};

#include "test.h"
#include <fstream>


sample::sample(){
	val = new double* [d];
	for (int i = 0; i<d; ++i){
	double* val[i] = new double [M];
	}
}

sample::~sample(){
	delete val;
}

int main(){
sample smp;
}


I get the error
1
2
3
$g++ test.cpp -o test.exe
test.cpp: In constructor `sample::sample()':
test.cpp:7: error: variable-sized object `val' may not be initialized


I can't understand what the problem is.
The reason of the error is statement

double* val[i] = new double [M];

in the constructor. I think you meant

val[i] = new double [M];

Also you incorrectly delete val in the destructor.
As a C++ programmer, you are encouraged to use initialization lists for constructors.

Try this (code wasn't tested):

1
2
3
4
5
sample::sample(): val(new double* [d]){
	for (int i = 0; i<d; ++i){
	val[i] = new double [M];
	}
}
Last edited on

@Catfish3
As a C++ programmer, you are encouraged to use initialization lists for constructors.

Try this (code wasn't tested):

1
2
3
4
5
sample::sample(): val(new double* [d]){
	for (int i = 0; i<d; ++i){
	double* val[i] = new double [M];
	}
} 



As I pointed out above this code is invalid.:)
Indeed, vlad. I saw that in the last moment.
Topic archived. No new replies allowed.