Custom Data Type Structure In C

Creating & Using your Own Data Types with Struct

    Introduction

    One vital task you will continually be doing is handling and processing data. Using the basic data types like we have done in previous tutorials is good, but when you will deal with more sophisticated tasks like managing and processing data with files and databases; then the only thing that can make the process easier and more structured is using struct.

    What is a Struct?

    Struct is a data container structure, which allows you to create a data type, which allows you to include different data type variable items in a one place.

    	//	CREATE A STRUCT WITH MEMBER VARIABLES
    	struct StudentData {
    		char student_name [50];
    		int student_age;
    		char student_grade;
    	};

    Once you have created the struct, you can use it just like any data type. So to declare the struct by creating an normal identifier as you would with any variable item by doing it like this.

    	// DECLARE A NEW STRUCT VARIABLE
    	struct StudentData student;

    Using Structs

    With that done, you can use the member variables in the same way you do with any variable types. Whether you want to retrieve the value of a member variable item, or assign a value. To get access to the members you need to use the member access operator (which is a full stop), which is used to access the variable within the struct. It is used like this.

    	// ASSIGN VALUES TO THE STRUCT MEMBERS
    	student.student_name = "Lee Jones";
    	student.student_age = 21;
    	student.student_grade = "B";
    	
    	// NOW PRINTING THE STUDENT DETAILS USING STRUCT VARIABLE
    	printf("Student Name : %s", student.student_name);
    	printf("\nStudent Age : %d",student.student_age);
    	printf("\nStudent Grade : %c",student.student_grade);

    The best thing is, you can use the struct item the same way you would use any other data type variable. You can even pass a struct defined variable through a function argument parameter, or return a struct defined variable item. We have gone over the basic way to set up and use a struct.

    Example Code In Detail

    In our program example it is not too dissimilar as it allows a user to enter a User Name and their Age. First, we need to create the struct, which we will need to collect and display the data.

    // THE CREATION OF THE STRUCT
    struct UserDetails
    {
    	// MEMBER IDENTIFIER VARIABLES
    	char user_name[40];
    	int age;
    };

    Once the program enters the int main section of the code, we will declare the struct variable item.

    int main()
    {
    	// DECLARE THE STRUCT DATA ITEM
    	struct UserDetails details;

    Once that is declared, we are ready to work with the struct variable item. First we use scanf to collect the data, first the name has to be entered, which has to be under 40 chars long. As you can see scanf format string uses a whitespace reader (which looks like [^\n], as it reads the whole input line), so we can read both the user's first and second name.

    	// NOW ENTER THE USER'S NAME AND AGE INTO
    	// THE STRUCT MEMBER VARIABLES
    	printf("Enter the User's Name : ");
    	scanf("%[^\n]",&details.user_name);
    
    	// CLEAN AWAY ANY EXCESS INPUT BEFORE PROCESSING THE SECOND INPUT
    	fflush(stdin);

    Once you have input the name, the fflush function clears the buffer so the user can enter the age again into scanf. Once the data is processed into the input buffers, the code will print a message, which includes the user's name and age.

    	printf("\nEnter their Age : ");
    	scanf("%d",&details.age);
    
    	// PRINT THE DETAILS FROM THE STRUCT
    	printf("\nNow we know that the User's Name is %s, and User's age is %d", 
    		details.user_name, details.age);
    	

    Once that is complete the code will close once you press Enter. As you can see it is no different to using your normal data type variables. You can include as many variable members you want.

    Summary

    If you use struct in C++, bare in mind it is different to the struct we are covering in this article for C. In C, you can only store member variables, as it is a simple data container of member variables. In C++, they are another alternative to a class object, which means that you can not only store member variables, but also member function, just like a normal class; only difference is that in a C++ Struct, the members are by default public, and Classes are by default private. In C when you declare a struct variable instance, you have to use the struct  keyword, when you do the same in C++, you do not use the keyword. And in C++, as it is a Object Orientation Programming (OOP) Language  structs have more added features, which are similar to other OOP class structures. There are similarities in some way, but in execution between the two languages, they can be different. More details about OOP are covered in C++ tutorials.

    /*
    	STRUCTURES	ReliantCode
    	Using Struct in C
    */
    
    #include <stdio.h>
    
    // THE CREATION OF THE STRUCT
    struct UserDetails
    {
    	// MEMBER IDENTIFIER VARIABLES
    	char user_name[40];
    	int age;
    };
    
    int main()
    {
    	// DECLARE THE STRUCT DATA ITEM
    	struct UserDetails details;
    
    	// NOW ENTER THE USER'S NAME AND AGE INTO
    	// THE STRUCT MEMBER VARIABLES
    	printf("Enter the User's Name : ");
    	scanf("%[^\n]",&details.user_name);
    
    	// CLEAN AWAY ANY EXCESS INPUT BEFORE PROCESSING THE SECOND INPUT
    	fflush(stdin);
    
    	printf("\nEnter their Age : ");
    	scanf("%d",&details.age);
    
    	// PRINT THE DETAILS FROM THE STRUCT
    	printf("\nNow we know that the User's Name is %s, and User's Age is %d", 
    		details.user_name, details.age);
    
    	// PRESS RETURN TO EXIT
    	fflush(stdin);
    	getchar();
    }
    blog comments powered by Disqus
    Download Files Here

    PDF Version Here

    Download this Article in PDF

    Feedback on Article

    Report Bugs, Errors or Send Feedback

    MD5 Hash Check : What is MD5?