此代码应输出0 0.25 0.5 0.75 1,而不是输出零。那是为什么?
定义函数u(x)= x;
void pde_advect_IC(double* x, double* u)
{
int N = sizeof(x) / sizeof(x[0]); //size of vector u
for (int i = 0; i <= N; i++)
u[i] = x[i];
}
以下是实施:
int main()
{
double a = 0.0;
double b = 1.0;
int nx = 4;
double dx = (b - a) / double(nx);
double xx[nx + 1]; //array xx with intervals
// allocate memory for vectors of solutions u0
double* u0 = new double [nx + 1];
//fill in array x
for (int i = 0; i <= nx; i++)
xx[i] = a + double(i) * dx;
pde_advect_IC(xx, u0); // u0 = x (initial conditions)
for (int i = 0; i <= nx; i++)
cout<<u0[i]<<endl;
// de-allocate memory of u0
delete [] u0;
delete [] u1;
return 0;
}
答案 0 :(得分:3)
你不能使用sizeof(x)
因为它会返回指针的大小,而不是你认为传递给它的数组。您必须使用第三个参数指定大小,或使用更方便的内容,例如std::vector
并使用size()
。
答案 1 :(得分:0)
这很有效。
void push_front( const Object& item )
{
Node * new_node = new Node( item );
++size;
if ( size == 1 )
{
new_node->next = nullptr;
first = last = new_node;
return;
}
new_node->next = first;
first = new_node;
}
请注意,我向#include <iostream>
#include <cstdlib>
using namespace std;
void pde_advect_IC(double* x, double* u, const int& N)
{
for (int i = 0; i < N; i++)
u[i] = x[i];
}
int main()
{
double a = 0.0;
double b = 1.0;
int nx = 4;
double dx = (b - a) / double(nx);
double xx[nx + 1]; //array xx with intervals
// allocate memory for vectors of solutions u0
double* u0 = new double [nx + 1];
//fill in array x
for (int i = 0; i <= nx; i++)
xx[i] = a + double(i) * dx;
pde_advect_IC(xx, u0, nx + 1); // u0 = x (initial conditions)
for (int i = 0; i <= nx; i++)
cout << u0[i] << endl;
// de-allocate memory of u0
delete [] u0;
return 0;
}
添加了const int& N
,以便通过pde_advect_IC()
将其传递给数组的大小,以确保它不会被错误地修改。
请注意,使用const reference
的诀窍不可以使用指针。