调用函数后无法访问数组
Have no access to an array after a function has been called
我正在尝试更改 func() 中 ydot[] 的值,以便我可以在我的 ode() 函数中使用它。但是,在调用 func() 之后,我似乎无法再访问 ydot[]。我将 func() 作为函数指针传递给 ode(),称为 dydt。这是我的两个功能:
void func(double t, double y[], double ydot[])
{
for(int i = 0; i < 18; i++){
ydot[i] = y[i]+1;
}
}
typedef void (*dydt_func)(double t, double y[ ], double ydot[ ]);
void ode(double y0[ ], double yend[ ], int len, double t0,
double t1, dydt_func dydt)
{
double ydot[len];
dydt = &func;
//This prints out all the value of ydot[] just fine
for (int i = 0; i < 18; i++){
cout << ydot[i] << ",";
}
dydt(t1, y0, ydot);
//This SHOULD print all the revised value of ydot[]
//But I get an error instead:
//Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
for (int i = 0; i < 18; i++){
cout << ydot[i] << ",";
}
};
在调用 dydt() 之前,我可以访问 ydot[]。我使用函数指针的方式有问题吗?或者我应该将 ydot[] 或其他东西的指针传递给 func() 吗?谢谢大家的帮助!
C++ 没有像 C 那样的可变长度数组,因此您需要使用 new
来分配可变大小的数组,或者使用 std::vector
而不是数组。
您需要将数组的大小传递给 func
,以便它可以将更新的元素数量限制为该大小。如果数组长度小于 18,您的代码将有未定义的行为。
void func(double t, double y[], double ydot[], int len)
{
for(int i = 0; i < len; i++){
ydot[i] = y[i]+1;
}
}
typedef void (*dydt_func)(double t, double y[ ], double ydot[ ], int len);
void ode(double y0[ ], double yend[ ], int len, double t0,
double t1, dydt_func dydt)
{
double *ydot = new double[len];
dydt = &func;
//This prints out all the value of ydot[] just fine
for (int i = 0; i < 18; i++){
cout << ydot[i] << ",";
}
dydt(t1, y0, ydot, len);
for (int i = 0; i < len; i++){
cout << ydot[i] << ",";
}
};
我正在尝试更改 func() 中 ydot[] 的值,以便我可以在我的 ode() 函数中使用它。但是,在调用 func() 之后,我似乎无法再访问 ydot[]。我将 func() 作为函数指针传递给 ode(),称为 dydt。这是我的两个功能:
void func(double t, double y[], double ydot[])
{
for(int i = 0; i < 18; i++){
ydot[i] = y[i]+1;
}
}
typedef void (*dydt_func)(double t, double y[ ], double ydot[ ]);
void ode(double y0[ ], double yend[ ], int len, double t0,
double t1, dydt_func dydt)
{
double ydot[len];
dydt = &func;
//This prints out all the value of ydot[] just fine
for (int i = 0; i < 18; i++){
cout << ydot[i] << ",";
}
dydt(t1, y0, ydot);
//This SHOULD print all the revised value of ydot[]
//But I get an error instead:
//Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
for (int i = 0; i < 18; i++){
cout << ydot[i] << ",";
}
};
在调用 dydt() 之前,我可以访问 ydot[]。我使用函数指针的方式有问题吗?或者我应该将 ydot[] 或其他东西的指针传递给 func() 吗?谢谢大家的帮助!
C++ 没有像 C 那样的可变长度数组,因此您需要使用 new
来分配可变大小的数组,或者使用 std::vector
而不是数组。
您需要将数组的大小传递给 func
,以便它可以将更新的元素数量限制为该大小。如果数组长度小于 18,您的代码将有未定义的行为。
void func(double t, double y[], double ydot[], int len)
{
for(int i = 0; i < len; i++){
ydot[i] = y[i]+1;
}
}
typedef void (*dydt_func)(double t, double y[ ], double ydot[ ], int len);
void ode(double y0[ ], double yend[ ], int len, double t0,
double t1, dydt_func dydt)
{
double *ydot = new double[len];
dydt = &func;
//This prints out all the value of ydot[] just fine
for (int i = 0; i < 18; i++){
cout << ydot[i] << ",";
}
dydt(t1, y0, ydot, len);
for (int i = 0; i < len; i++){
cout << ydot[i] << ",";
}
};