fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <assert.h>
  5.  
  6. typedef struct {
  7. int x, y;
  8. } Point;
  9.  
  10. typedef struct {
  11. char label[8];
  12. const char *desc;
  13. Point vertices[]; // Flexible array member
  14. } Polygon;
  15.  
  16. Polygon *make_polygon(const char *label, const char *desc, size_t nPoints, Point vertices[nPoints]) {
  17. // Allocate memory for the Polygon structure and its vertices array
  18. Polygon *p = malloc(sizeof(Polygon) + nPoints * sizeof(Point));
  19.  
  20. // Ensure the label can fit into the structure
  21. assert(strlen(label) < sizeof(p->label));
  22.  
  23. // Copy label and description to the polygon
  24. strcpy(p->label, label);
  25. p->desc = desc;
  26.  
  27. // Copy the vertices array into the polygon
  28. memcpy(p->vertices, vertices, nPoints * sizeof(Point));
  29.  
  30. return p;
  31. }
  32.  
  33. void f() {
  34. // Create a triangle polygon using `make_polygon()`
  35. Polygon *triangle = make_polygon("tr_1", "base", 3, (Point[]) {
  36. { .x = 0, .y = 0 },
  37. { .x = 64, .y = 10 },
  38. { .x = 100, .y = 32 }
  39. });
  40.  
  41. // Access the 3rd vertex
  42. Point *v2 = &triangle->vertices[2];
  43.  
  44. // Get the x-coordinate of the 3rd vertex
  45. int x2 = v2->x;
  46.  
  47. // Access a byte after the x value of the 3rd vertex
  48. char c = *((char *)(&v2->x) + 4); // This accesses the memory directly
  49.  
  50. // Clean up allocated memory
  51. free(triangle);
  52. }
  53.  
  54. int main() {
  55. printf("Start\n");
  56. f();
  57. printf("End");
  58. return 0;
  59. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
Start
End