/************** * c_object_template.c * * a template for working with "data objects" in C. * * These "objects" contain data storage, not methods. * Instead create functions that take the data storage as their first arg. * * The key ideas are * i) define new types made up of struct * ii) treat the pointer to that struct as the "object". * iii) use malloc to create (memory allocate) these things * iv) access the fields within the struct with the -> operator . * * For example, this is legal C syntax : * * struct _foo { * int bar; * int baz; * } * * struct _foo f1; * struct _foo f2; * * f1.bar = 3; * f2.baz = 4; * * The "struct _foo" words are treated as one thing, a type, * similar to "int". So "struct _foo f1" is a declaration * that f1 is a "struct _foo". * * But these structures can get big ... think arrays of * of thousands of points. In practice we usually want * a reference to one of these ... a pointer to a struct _foo. * * The syntax is : * * structure.field * (*ptr_to_struct).field // dereference a pointer first * ptr_to_struct->field // same thing * ****************************************************/ // You need this for malloc() #include <stdlib.h> // ... and this for printf. #include <stdio.h> // ... and this for strcpy #include <string.h> // Define "mything" as a pointer to "struct _mything". typedef struct _mything *mything; // Then define what "struct _mything" is. // Doing things in this order allows this definition // to include mything, for example a Node in a linked list // that has a pointer to another Node. struct _mything { // interior data fields defined here. For example: int count; // an integer value char name[32]; // a string of 32 characters. }; // Define a "create one of these" function. mything new_mything(){ // allocate a mything block of memory; return a pointer to it. mything newthing = malloc(sizeof(struct _mything)); newthing->count = 0; // initialize its count strcpy(newthing->name, ""); // copy empty string to it's name. return newthing; } int main(){ mything george = new_mything(); // create one george->count = 33; // put stuff in it strcpy(george->name, "George"); // and give it a name. printf("The object has count=%i and name=%s.\n", george->count, george->name); return 0; }