将float[]作为float*参数传递的问题
我会尽量直截了当。
我有一个练习要解决,我在网上搜索了很多,但找不到我的问题所在。
因为这是一个“原样”练习,我不能将 float* 修改为 float[],我必须使用给定的值和给定的函数签名。我只能使用 setWeight 函数的包含。
考虑以下:
class Train
{
protected:
float* weight;
public:
setWeight(float* weight)
{
this->weight = weight;
}
}
然后在主要我调用以下内容:
main()
{
float weights[] = { 30.5f, 20.0f, 12.7f, 15.88f };
train.setWeight(weights);
}
当我查看调试模式时,只有第一个值被传递。有人可以帮我吗?
回答
该程序没有做错任何事情,但您看错了。
In the debugger instead of reading train.weight and letting the debugger follow the pointer, try reading train.weight[0], train.weight[1], and train.weight[3]
- With Visual Studio you can tell the debugger a pointer points to an array, and how many elements come after it. If you have a pointer `ptr` which points to an array of 5 elements you can put a watch on `ptr,5` and the debugger will show the 5 values as-if `ptr` was an array.