我有一个嵌套结构问题的地址,我现在已经有一段时间没能解决了。
所以我有一个包含 sensorStruct 的 ModuleStruct。 将地址传递给 main 中的 ModuleStruct 没有问题。但是当我确实想将地址传递给内部结构“SensorStruct”以便 readVoltage 函数可以存储值时,它失败了。 一直在谷歌搜索和检查 StackOverflow,但没有找到任何有效的方法。我希望我只是做了一些愚蠢的事情,所以很容易让它继续下去。
如果有人能指出我正确的方向,我会非常高兴 (*puufh ;) )
typedef struct
{
int32_t Voltage;
int32_t Current;
}SensorStruct;
typedef struct
{
SensorStruct SensorData;
}ModuleStruct;
int main(void)
{
ModuleStruct Module_Data;
Sensor_Collect(&Module_Data);
}
void Sensor_Collect(ModuleStruct *Module_Data)
{
/// Here is the problem, I do not know how to pass the address of the SensorStruct
ReadVoltage(Module_Data->SensorData);
}
void ReadVoltage(SensorStruct *Sensor_Data)
{
Sensor_Data->Voltage = 5;
Sensor_Data->Current = 3;
}
最佳答案
有效的代码。请注意,Sensor_Collect
函数是在 ReadVoltage
函数之后定义的,因此它在调用时知道它的类型。始终在打开所有警告的情况下编译代码。
#include <stdio.h>
#include <stdint.h>
typedef struct {
int32_t Voltage;
int32_t Current;
} SensorStruct;
typedef struct {
SensorStruct SensorData;
} ModuleStruct;
void ReadVoltage(SensorStruct *Sensor_Data) {
Sensor_Data->Voltage = 5;
Sensor_Data->Current = 3;
}
void Sensor_Collect(ModuleStruct *Module_Data) {
ReadVoltage(&(Module_Data->SensorData));
}
int main(void) {
ModuleStruct Module_Data;
Sensor_Collect(&Module_Data);
printf("voltage: %d\n", Module_Data.SensorData.Voltage);
printf("current: %d\n", Module_Data.SensorData.Current);
return 0;
}
关于C 将结构中的嵌套结构传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35588021/