structs in C


Overview: structs in C are Java classes with most of the functionality eliminated. (Of course historically structs came before classes.) In particular, structs are missing the following features of Java classes:

All that is left are a collection of public data members.


Initial C example: This presents a simple example of two structs, the first defining a point with integer coordinates, and the second defining a rectangle consisting of two points (the diagonal points): Simple structs.


Previous example in Java, back into C: This takes the previous C program, translates it into Java, and then more faithfully translates the Java back to C: Java version, back to C.


Structs and pointers to structs as parameters and as returned values: The important thing to realize is that if a "bare" struct is passed as a parameter or returned from a function, a copy is made and the copy is passed or returned. Here is an extended examples illustrating this: structs as parameters and returned values.


Other ways to use structs: There are other options in C for the use of structs, but we will avoid these in this course. For example, given the declaration:

Then the following are equaivalent: struct_name and struct tag_name.

It is also possible to declare a struct and to declare variables of the type of the struct at the same time, as in the following example:

Then student1, john_doe,and mary are all three variables of type struct student. This actually allocates storage.


Initializing structs with a {} list: In both C and Java one can initialize an array with a list of constants separated by commas and inside curley brackets. In C this works for structs also, but you can't do this in Java for classes. Here is an example:


Copyright © 2011, Neal R. Wagner. Permission is granted to access, download, share, and distribute, as long as this notice remains.