Skip to content

Instantly share code, notes, and snippets.

@Cilyan
Created March 31, 2015 16:28
Show Gist options
  • Save Cilyan/3aea714fe005bc795bde to your computer and use it in GitHub Desktop.
Save Cilyan/3aea714fe005bc795bde to your computer and use it in GitHub Desktop.
Strange nested construct of structures
#include <stdio.h>
#include <string.h>
/* gcc -Wall -Werror -std=c11 -pedantic -o robotc robot.c */
struct Robot_st {
int pos_x;
int pos_y;
struct BatteryStatus_st {
int capacity;
int load;
} battery;
};
int main(int argc, char **argv)
{
struct Robot_st my_robot = {2, 3, {200, 50}};
struct BatteryStatus_st battery_snapshot;
memcpy(
&battery_snapshot,
&my_robot.battery,
sizeof(struct BatteryStatus_st)
);
printf("robot position: %d,%d\n", my_robot.pos_x, my_robot.pos_y);
printf("battery load: %d%%\n", battery_snapshot.load);
return 0;
}
#include <stdio.h>
#include <string.h>
/* g++ -Wall -Werror -std=c++11 -pedantic -o robotcpp robot.cpp */
struct Robot_st {
int pos_x;
int pos_y;
struct BatteryStatus_st {
int capacity;
int load;
} battery;
};
int main(int argc, char **argv)
{
struct Robot_st my_robot = {2, 3, {200, 50}};
struct Robot_st::BatteryStatus_st battery_snapshot;
memcpy(
&battery_snapshot,
&my_robot.battery,
sizeof(struct Robot_st::BatteryStatus_st)
);
printf("robot position: %d,%d\n", my_robot.pos_x, my_robot.pos_y);
printf("battery load: %d%%\n", my_robot.battery.load);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment