Creating a new point in c
In C, you can create a new point (or a struct with two integer fields, x and y) using the following ways:
Method 1: Using a struct
#include <stdio.h>
typedef struct {
int x;
int y;
} Point;
int main() {
Point p;
p.x = 10;
p.y = 20;
printf("Point: (%d, %d)\n", p.x, p.y);
return 0;
}
Method 2: Using a union
#include <stdio.h>
typedef union {
int x;
int y;
} Point;
int main() {
Point p;
p.x = 10;
printf("Point: (%d,?)\n", p.x);
p.y = 20;
printf("Point: (?, %d)\n", p.y);
return 0;
}
Method 3: Using a struct with a constructor function
#include <stdio.h>
typedef struct {
int x;
int y;
} Point;
Point* createPoint(int x, int y) {
Point* p = (Point*)malloc(sizeof(Point));
p->x = x;
p->y = y;
return p;
}
int main() {
Point* p = createPoint(10, 20);
printf("Point: (%d, %d)\n", p->x, p->y);
free(p);
return 0;
}
Method 4: Using a struct with a constructor function and destructor
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int x;
int y;
} Point;
Point* createPoint(int x, int y) {
Point* p = (Point*)malloc(sizeof(Point));
p->x = x;
p->y = y;
return p;
}
void destroyPoint(Point* p) {
free(p);
}
int main() {
Point* p = createPoint(10, 20);
printf("Point: (%d, %d)\n", p->x, p->y);
destroyPoint(p);
return 0;
}
Note: In the above examples, the Point
struct is used to represent a point in a 2D space. The x
and y
fields represent the coordinates of the point.