Creating and Using Structs in C
The following source code demonstrates how to define a custom data structure ( struct
in C)
The main program makes two instances of the struct point and shows how to access the member variables as well as write
and call functions that use the struct as a type for input parameters.
struct-demo.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
struct point {
double x;
double y;
char label[100];
};
void printPointInfo(struct point p){
printf("(%+5.1f,%+5.1f) - %s\n", p.x, p.y, p.label);
}
double getDistance(struct point a, struct point b){
double xdist = a.x - b.x;
double ydist = a.y - b.y;
return sqrt((xdist*xdist) + (ydist*ydist));
}
int main(void) {
struct point p1, p2;
//setting member values in p1
p1.x = -4;
p1.y = -1;
strcpy(p1.label, "first point");
//setting member alues in p2
p2.x = -1;
p2.y = -5;
strcpy(p2.label, "second point");
printPointInfo(p1);
printPointInfo(p2);
double dist = getDistance (p1,p2);
printf("Distance = %f", dist);
return 0;
}