Hi everyone:

I am fairly new to c++. I have created a dynamic array, but I am having trouble initializing it. My goal is to create a grid, and then assign an initial condition (for example, initial temperature = some value) on the grid points.

I know that it would be straightforward to use a vector, for example:

vector<double> u(I, 0.5);

but I need to use an array in this case.

Here is what I've done so far:

int I;
int i;                

double* u  ;                

u = new double[I*sizeof(double)];

for( i=0 ; i < I ; i++ ) 
	{
        e     = 0.5;
	u[i]  = e;  // I have also tried u[i] = {0.5};
		
		cout << "The vector u[i] contains:\n";
		for (i=0 ; i < I ; i++ )
		{
			cout << u[i] << endl;
		}
	}

The problem is that the result is this:
The vector u contains:
0
0.5
0
0
0
0
0
0
0
0
logout

I would very much appreciate it if anyone could suggest why only one of the grid points has the value I want (0.5) and what I might do to assign 0.5 on all the grid points.

Thank you for your help.

Recommended Answers

All 3 Replies

>>u = new double[I*sizeof(double)];

No! This is not C. In C++ its used like this :
u = new double[ I ];

The value inside [ ], is the number of elements. No need for the sizeof.

Put your printing loop out side separately. Like this :

void Foo(const int Size, const double value = 0 )
{
   double *Array = new double[ Size];
  //initialize it
   for( int i = 0; i != Size; ++i){
     Array[i] = value;
   }

   //print it
   for(int i = 0; i != Size; ++i){  
     cout << Array[i] << " ";
  }
}

>>u = new double[I*sizeof(double)];

No! This is not C. In C++ its used like this :
u = new double[ I ];

The value inside [ ], is the number of elements. No need for the sizeof.

Put your printing loop out side separately. Like this :

void Foo(const int Size, const double value = 0 )
{
   double *Array = new double[ Size];
  //initialize it
   for( int i = 0; i != Size; ++i){
     Array[i] = value;
   }

   //print it
   for(int i = 0; i != Size; ++i){  
     cout << Array[i] << " ";
  }
}

Hi firstPerson:

Thanks a lot! That does the trick. Much appreciated.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.