C
Beginner
1 min read
Defining Structs and typedef
Example
#include <stdio.h>
#include <string.h>
/* Struct with typedef */
typedef struct {
double x;
double y;
} Point;
typedef struct {
char name[64];
int id;
double salary;
} Employee;
/* Pass by pointer for efficiency */
void give_raise(Employee *emp, double percent)
{
emp->salary *= (1.0 + percent / 100.0);
}
double distance(Point a, Point b)
{
double dx = a.x - b.x;
double dy = a.y - b.y;
/* Approximation without <math.h> for brevity */
double sq = dx * dx + dy * dy;
/* Newton-Raphson sqrt approximation */
double r = sq;
for (int i = 0; i < 20; i++)
r = (r + sq / r) / 2.0;
return r;
}
int main(void)
{
Point p1 = {0.0, 0.0};
Point p2 = {3.0, 4.0};
printf("Distance: %.2f\n", distance(p1, p2)); /* 5.00 */
Employee emp;
strncpy(emp.name, "Alice", sizeof(emp.name) - 1);
emp.id = 101;
emp.salary = 50000.0;
printf("Before raise: %.2f\n", emp.salary);
give_raise(&emp, 10.0);
printf("After 10%% raise: %.2f\n", emp.salary);
/* Struct assignment (shallow copy) */
Employee copy = emp;
copy.salary = 1.0;
printf("Original salary unchanged: %.2f\n", emp.salary);
return 0;
}