#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
#define MAX 100
struct point {
int x;
int y;
};
void addOneByValue(struct point pt){
pt.x++;
pt.y++;
}
void addOneByReference(struct point *pt){
pt->x++;
pt->y++;
}
void printPoint(char *label, struct point *pt){
printf("%s (%d, %d)\n", label, pt->x, pt->y);
}
void staticArrayTest(){
printf("staticArrayTest()\n");
struct point points[SIZE];
for(int i = 0; i < SIZE; i++){
points[i].x = rand() % MAX;
points[i].y = rand() % MAX;
}
for(int i = 0; i < SIZE; i++){
char label[MAX];
sprintf(label, "points[%3d]:", i);
printPoint(label, &points[i]);
}
printf("\n");
}
void dynamicArrayTest(){
printf("dynamicArrayTest()\n");
struct point *points;
points = (struct point *)malloc(SIZE * sizeof(struct point));
for(int i = 0; i < SIZE; i++){
points[i].x = rand() % MAX;
points[i].y = rand() % MAX;
}
for(int i = 0; i < SIZE; i++){
char label[MAX];
sprintf(label, "points[%3d]:", i);
printPoint(label, &points[i]);
}
free(points);
printf("\n");
}
void dynamicArrayOfPointerTest(){
printf("dynamicArrayOfPointerTest()\n");
struct point **points;
points = (struct point **)malloc(SIZE * sizeof(struct point *));
for(int i = 0; i < SIZE; i++){
points[i] = (struct point *)malloc(sizeof(struct point));
points[i]->x = rand() % MAX;
points[i]->y = rand() % MAX;
}
for(int i = 0; i < SIZE; i++){
char label[MAX];
sprintf(label, "points[%3d]:", i);
printPoint(label, points[i]);
}
for(int i = 0; i < SIZE; i++){
free(points[i]);
}
free(points);
printf("\n");
}
void array2DTest(){
printf("array2DTest()\n");
int points[SIZE][2];
for(int i = 0; i < SIZE; i++){
points[i][0] = rand() % MAX;
points[i][1] = rand() % MAX;
}
for(int i = 0; i < SIZE; i++){
printf("(%d, %d)\n", points[i][0], points[i][1]);
}
printf("\n");
}
void array1DTest(){
printf("array1DTest()\n");
int points[SIZE*2];
for(int i = 0; i < SIZE*2; i++){
points[i] = rand() % MAX;
}
for(int i = 0; i < SIZE; i++){
printf("(%d, %d)\n", points[2*i], points[2*i+1]);
}
printf("\n");
}
int main(int argc, char* argv[]){
struct point p1, p2;
p1.x = 3;
p1.y = 12;
p2.x = 15;
p2.y = -4;
printPoint("Point one:", &p1);
printPoint("Point two:", &p2);
addOneByValue(p1);
printPoint("Point one after addOneByValue:", &p1);
addOneByReference(&p1);
printPoint("Point one after addOneByReference:",&p1);
printf("\n");
staticArrayTest();
dynamicArrayTest();
dynamicArrayOfPointerTest();
array2DTest();
}