Reputation: 53
I'm trying to pass struct parts to functions, is this possible?
I want to create general functions like the setLeftMotorSpeed
below and pass them anything i want, in this case i need to set the robot.leftMotorSpeed
via a pointer
Example:
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;
}
}
Upvotes: 1
Views: 1353
Reputation: 4069
Your code will be simpler if you simply pass a pointer to the struct and let the function modify the fields that it needs to. Only pass individual fields (or pointers to them) if the function needs to draw information from more than one robot. Your setLeftMotorSpeed
function could look something like:
void setLeftMotorSpeed(robot *rptr, int speed)
{
rptr->leftMotorSpeed = speed;
}
This is a trivial example, of course. The moveAtSpeed
function might also use a robot pointer, if the intent of that function is to move just one particular robot.
This is the beginning of object-oriented thinking, by the way. You've built a struct to describe a robot. The next step is to think of functions that act on one of those robot structs as logical operations on the whole robot, so that the code that requests a robot "speed up" can be written without worrying about the bit-by-bit details of how that gets done.
PS: Using a pointer for command
is not recommended. Simple read-only values should be passed as normal arguments. It takes extra time and code at each use to "dereference" a pointer, and the extra source code complexity isn't needed. This is a small difference, but the cumulative effect of doing things like this over a whole program can be significant.
Upvotes: 1
Reputation: 399949
The chooseRequest()
function must take a pointer to a robot
, in order to be able to modify it.
As written, you're just modifying a local copy which ceases to exist when the function exits.
Upvotes: 2
Reputation: 53016
Just
robot my_robot;
setLeftMotorSpeed(&speed, &my_robot.leftMotorSpeed, &rightMotorSpeed);
this will work and set the value of my_robot.leftMotorSpeed
as you apparently require it to.
Upvotes: 3