C 将结构中的嵌套结构传递给函数?

标签 c function pointers struct nested

我有一个嵌套结构问题的地址,我现在已经有一段时间没能解决了。

所以我有一个包含 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/

相关文章:

C void函数修改指针数组

c - 如何使用 MPI_Abort() 终止其他处理器

objective-c - 为什么 Cocoa 开发中没有动机传递指针?

c - 字符串复制函数: simple issue

c++ - 将成员函数从 C++ CLI 传递到 native C 回调

c - 从双链表中删除项目

c - 当显示变量 "int a = 011"的值时,我得到 9。为什么?

c - 如何使用 MPI 传递带有动态数组的自定义结构?

c - 在 C 中使用函数原型(prototype)和数组

java - 流口水功能