Structures in c are used to represent data what have connections to each other in a single variable. This could be a record from a database.

Structures can be declared outside the functions to give access for all the function in the program. Other options for declaration is in the main header file(good idea), or inside main or other function which would make it available only for local use. A good practice is to not only declare the structure by create a type of that structure. This can make the code more compact and readable at the same time. With other words we can create an alias for structure.
With an example:

//creating a student type
typedef struct student_record STUDENT;
//general structure declaration
struct student_record{
    unsigned int id;
    char *firstName;
    char *lastName;
};

To use the student_record structure:

main(){
   STUDENT firstStudent = {1, "John", "Doe"};//using the alias
   student_struct secondStudent = {0};// initializing all to 0 where char will be null

   firstStudent.id = 777;
   firstStudent.firstName = "Jane";//use the dot(.) notation for access the elements of structure
}

A more advanced way of using structs is by implementing pointers, where the same pointer rules apply as with other variable types like pointer can only be of type it points to etc. There are two ways to access structure pointer elements, pointer element with dot notation or the arrow notation.
With an example:

main(){
   STUDENT firstStudent = {0};
   STUDENT *ptrFirstStudent = &firstStudent;

   (*ptrFirstStudent).id = 777;
   ptrFirstStudent->firstName = "Jane";
}

/*struct_function: just showing how to pass, and access pointer structure elements*/
void struct_function(STUDENT *ptrFS){
    (*ptrFirstStudent).id = 777;
   ptrFirstStudent->firstName = "Jane";
}

To understand c structure basics you should have an understanding of pointer, arrays. You can find articles about these topics in the C category.

Share This