我已经搜索并找到了许多类似的问题(无疑是很好的答案),但是我还没有找到我完全理解的问题。我找到了一个可行的解决方案,实际上我只是想了解在第一个示例中我做错了什么...
我编写了一个函数,该函数使用声明通过原始加速度计值计算俯仰/横滚:
uint8_t calcPitchRoll (imu_t * imu, float * pitch, float * roll);
调用函数看起来像(参考行号):
518 float * pRollValue, * pPitchValue; // prepare pointers to floats to store results
519 *pRollValue = 0; // initialize variables
520 *pPitchValue = 0; // initialize variables
521 calcPitchRoll (imu, pPitchValue, pRollValue);
但是,这会导致编译器警告:
main.c:519:25: warning: 'pRollValue' may be used uninitialized in this function
main.c:521:26: warning: 'pPitchValue' may be used uninitialized in this function
但是下面的方法起作用:
float PitchValue, RollValue = 0;
float * pRollValue = &RollValue;
float * pPitchValue = &PitchValue;
calcPitchRoll (imu, pPitchValue, pRollValue);
对我来说,调用calcPitchRoll函数时,两个示例似乎都具有相同的“状态”,但是编译器不同意。
[我(认为我)理解的是,*pRollValue = 0
将该值写入变量,因此我认为此时该变量已在空间中分配了一个值。这是不正确的理解吗?
您的两个代码示例有很大的不同。
看看这个:
518 float * pRollValue, * pPitchValue; // Here pRollValue is uninitialized
519 *pRollValue = 0; // Here you dereference pRollValue (due to the *)
^
| // So you dereference an uninitialized pointer
|
Dereference of uninitialized pointer
这里
float PitchValue, RollValue = 0;
float * pRollValue = &RollValue; // You define a pointer and at the
// same time you initializes it to
// point to a float
所以这两个代码部分完全不同。
所以您需要了解指向T型对象的指针和T型对象之间的区别。
类似代码
float * pF;
将为您保留一个指向浮点数的指针提供记忆,但没有地方可以存储浮点数本身。您需要为指针分配一个值,使其指向浮点数。
所以您需要类似的东西:
float * pF;
float myFloatVariable;
pF = &myFloatVariable; // Now pF points to myFloatVariable
*pF = 42; // These two statements both sets
myFloatVariable = 42; // the variable myFloatVariable to 42
另一种方法是动态分配-如:
float * pF = malloc(sizeof *pF);
assert(pF != NULL);
*pF = 42; // This sets the dynamic allocated float to 42