c - 如何将结构属性作为参数传递

标签 c struct

我正在尝试将结构部分传递给函数,这可能吗? 我想创建像下面的 setLeftMotorSpeed 这样的通用函数,并向它们传递我想要的任何东西,在这种情况下,我需要通过指针设置 robot.leftMotorSpeed

例子:

typedef struct
{
    int maximumSpeed;
    int leftMotorSpeed;
    int rightMotorSpeed;
    int timesAboveMaximumSpeed;
    int batteryLevel;
    int collisions;

}robot;

void setLeftMotorSpeed(int *speed, int *leftMotorSpeed, int *rightMotorSpeed)
{
    *leftMotorSpeed = *speed;
}

void chooseRequest(int *command, int *speed, robot RP6)
{
    switch(*command)
    {
        case 1:
            setMaximumSpeed(speed, &RP6.maximumSpeed);
            break;
        case 2:
            getMaximumSpeed(speed, &RP6.maximumSpeed);
            break;
        case 3:
            setLeftMotorSpeed(speed, &RP6.leftMotorSpeed, &RP6.rightMotorSpeed);
            moveAtSpeed(RP6.leftMotorSpeed, RP6.rightMotorSpeed);       
            break;
        case 4:
            setRightMotorSpeed(speed, &RP6.leftMotorSpeed, &RP6.rightMotorSpeed);
            moveAtSpeed(RP6.leftMotorSpeed, RP6.rightMotorSpeed);
            break;
        case 5:
            break;
        case 6:
            break;
        case 7:
            break;
        default:
            break;
    }
}

最佳答案

只是

robot my_robot;

setLeftMotorSpeed(&speed, &my_robot.leftMotorSpeed, &rightMotorSpeed);

这将起作用并设置 my_robot.leftMotorSpeed 的值,因为您显然需要它。

关于c - 如何将结构属性作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28196039/

相关文章:

c - 不允许在 C51 中定义包含数组的结构?

c - 我不能在 Clion 中使用 getline

c - 在 Lua 中与嵌套函数一起使用 C 变量

c - 为什么星号三角形不能大于 23?

c# - 将具有另一个结构数组的结构从 C# 传递到 C (P/Invoke)

C++ 类内部结构在其方法中动态分配

C、如何在用户每次输入后停止stdin输出?

c - 这种分配风格是否定义明确?

ios - 键值 : on packed struct?

c - 动态结构数组