Created
February 27, 2025 09:49
-
-
Save DieracDelta/4732535f39447702c59263b3a3f4dab8 to your computer and use it in GitHub Desktop.
Structs v2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // I only have three examples. Ran out of ideas for more. | |
| // I can make VLA example if helpful? But, since this is discouraged in class, opted not to. | |
| #include <stdio.h> | |
| // EX0: No typedef | |
| struct Sensor { | |
| int id; | |
| double reading; | |
| }; | |
| int main(){ | |
| void ex_0(struct Sensor *s); | |
| // have to explicitly use struct keyword | |
| struct Sensor s = {1, 1.0}; | |
| ex_0(&s); | |
| return 0; | |
| } | |
| // have to explicitly use struct keyword | |
| void ex_0(struct Sensor *s) { | |
| printf("Sensor id: %d, reading: %.2f\n", s->id, s->reading); | |
| return; | |
| } | |
| // EX1: struct with typedef | |
| typedef struct { | |
| int id; | |
| float reading; | |
| } Sensor2; | |
| void main_2() { | |
| void ex_1(Sensor2 *s); | |
| // does not require struct keyword | |
| Sensor2 s2 = {1, 1.0}; | |
| ex_1(&s2); | |
| return; | |
| } | |
| // does not require struct keyword | |
| void ex_1(Sensor2 *s) { | |
| printf("Sensor id: %d, reading: %.2f\n", s->id, s->reading); | |
| return; | |
| } | |
| // EX2: struct containing pointer | |
| typedef struct { | |
| int num_values; | |
| double *values; | |
| } Measurement; | |
| void ex_2() { | |
| double ex_values[5] = {1.0, 2.0, 3.0, 4.0, 5.0}; | |
| Measurement m = {5, ex_values}; | |
| printf("These are the same %f %f", m.values[0], ex_values[0]); | |
| return; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment