Skip to content

Instantly share code, notes, and snippets.

@DieracDelta
Created February 26, 2025 18:46
Show Gist options
  • Select an option

  • Save DieracDelta/5a91d21113d73e6183d2d72d7bcda11b to your computer and use it in GitHub Desktop.

Select an option

Save DieracDelta/5a91d21113d73e6183d2d72d7bcda11b to your computer and use it in GitHub Desktop.
struct_examples
// 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;
};
// have to explicitly use struct keyword
void ex_0(struct Sensor *s) {
printf("Sensor id: %d, reading: %.2f\n", s->id, s->reading);
}
int main(){
// have to explicitly use struct keyword
struct Sensor s = {.id = 1, .reading = 1.0};
ex_0(&s);
return 0;
}
// EX1: struct with typedef
typedef struct {
int id;
float reading;
} Sensor2;
// does not require struct keyword
void ex_1(Sensor2 *s) {
printf("Sensor id: %d, reading: %.2f\n", s->id, s->reading);
}
void main_2() {
// does not require struct keyword
Sensor2 s2 = {.id = 1, .reading = 1.0};
ex_1(&s2);
}
// 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]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment