MC logo
C Structs
[^] Code Examples
<<String Error struct.c Point With Struct>>
 * Basic structs.
#include <stdio.h>
#include <string.h>

/* Struct is like a class w/o methods. */
struct fred {
        int m;
        char str[40];
        double d;
/* Notice the semicolon above. */

/* Print a fred, preceded by a message. */
void pfred(char *t, struct fred *fr)
        printf("%s: [ m = %d, str = %s, d = %f ]\n",
               t, fr->m, fr->str, fr->d);

int main()
        /* This declares a variable f1 which is a fred, and initializes it
           to the values indicated. */
        struct fred f1 = { 40, "Howdy", 5.498 };

        /* This declares two variables, an uninitialized fred and a pointer
           to a fred object. */
        struct fred f2, *fp;

        f2 = f1;
        pfred("f1", &f1);
        pfred("f2", &f2);

        f2.m += 10;
        strcat(f2.str, " there");
        f2.d = 16.0001;
        pfred("AA", &f2);

        fp = &f1;
        fp->m = -55;
        fp->str[3] = '\0';
        fp->d = 111.111;
        pfred("ZZ", &f1);

Structs are like classes, with all fields public and no methods. In C++, structs are extended into classes. Note that structs (and classes in C++) are not limited to references as in Java, though you can make pointers to them. Also, you can allocate them by simply declaring variables. There is no need to use a new to allocate.

In C, if s is a struct, you select fields with a dot, as s.f. If p is a pointer to a struct, you can select fields from the struct it points to with an arrow, as p->f. This is an abbreviation for (*p).f. This can be confusing, since the pointer (where you use the arrow) is more like a Java reference (where you use dot).
<<String Error Point With Struct>>