structs:
|
Similar Java Program | C Program Redone |
---|---|
public class Boxes { class Point { int x; int y; } class Rect { Point pt1; Point pt2; } public void makeBox() { Rect box = new Rect(); box.pt1 = new Point(); box.pt2 = new Point(); box.pt1.x = 3; box.pt1.y = 2; box.pt2.x = 11; box.pt2.y = 7; System.out.println( "width: " + width(box) + ", height: " + height(box)); } int width(Rect r) { return Math.abs(r.pt1.x - r.pt2.x); } int height(Rect r) { return Math.abs(r.pt1.y - r.pt2.y); } public static void main(String[] args) { Boxes b = new Boxes(); b.makeBox(); } } |
#include <stdio.h> struct point { int x; int y; }; struct rect { struct point *pt1; struct point *pt2; }; void makebox() { struct rect *box = (struct rect *)malloc(sizeof(struct rect)); box -> pt1 = (struct point *)malloc(sizeof(struct point)); box -> pt2 = (struct point *)malloc(sizeof(struct point)); box -> pt1 -> x = 3; box -> pt1 -> y = 2; box -> pt2 -> x = 11; box -> pt2 -> y = 7; printf("width: %i, height: %i\n", width(box), height(box)); } int width(struct rect *r) { return abs(r -> pt1 -> x - r -> pt2 -> x); } int height(struct rect *r) { return abs(r -> pt1 -> y - r -> pt2 -> y); } int main() { makebox(); } |
Output | |
% cc -o boxes boxes.c % boxes width: 8, height: 5 | % javac Boxes.java % java Boxes width: 8, height: 5 |