Structs in C

 

Like Java classes but without methods or public/private specifications.

 

Used to package related data together.

 

Example of defining a struct:

 

            struct Foo

            {

                        int x;

                        int array[100];

            };  /* note semi-colon here */

 

Where to define Structs

 

            Generally defined in a header file, e.g. lexer.h, along with function prototypes

 

            Can define them at the top of .c file

 

Declaration and Usage Example:

 

            struct Foo f;  // automatic allocation, all fields placed on stack

            f.x = 54;

            f.array[3]=9;

 

typedef allows you to declare instances of a struct without using keyword "struct"

 

        typedef struct

        {

                int x;

                int array[100];

        } Foo;

 

Foo is now a type that can be declared without "struct" in front of it:

 

        Foo f;

 

 

 

 

 

 

 

 

 

 

 

 

 

Passing Structs as Parameters

 

            Structs are passed by value, just like primitives

 

            void func(struct Foo foo)

            {

                        foo.x = 56;

                        foo.array[3]=55;

            }

            void main()

            {

                        struct Foo f; 

                        f.x = 54;

                        f.array[3]=9;

                        func(f);

                        // what are the values of f.x and f.array[3]

            }

 

To have changes occur, send a pointer to the struct

 

            struct Foo f; 

            f.x = 54;

            f.array[3]=9;

            func(&f);  /* & returns the address of a variable */

 

 and have the function accept a pointer:

 

            void func(struct Foo* p_foo)

            {

                        p_foo->x = 56;

                        p_foo->array[3]=55;

            }

 

            Note that -> is used to get to the fields of a pointer to a struct.

 

            -> is short-hand for   (*foo).x=56

 

In-Class Problem

 

            Define a struct InputStream with an array of chars and an index.

 

            In the main

 

                        set the array part of the struct to  ABCDEFGHIJ  using strcpy.

                        set the index part of the struct to 4.

                        write a function which accepts a pointer to the struct as a parameter and

                                    returns the character at the indexth location

                                    increments the index by 1.

                        call this function from your main program.