Structures (struct) in C Programming

Updated on July 9, 2018
rajkishor09 profile image

Raj is an ardent coder who loves exploring new technology. He is an IT pro with 9 years of exp in C#, Angular, React, Vue.

structure in c language
structure in c language

C Structure Introduction

We used variable in our C program to store value but one variable can store only single piece information (an integer can hold only one integer value) and to store similar type of values we had to declare many variables. To overcome this problem we used array which can hold numbers of similar data type. But array too have some limitations, like in our real world application we deal with set of dissimilar data types and single array cannot store dissimilar data.

For example think about storing book information or product information, a product can have different information to store like product code (an integer), product name (a char array), product price (a float) etc. And to store 20 products information we can declare integer array for product code, 2D character array for storing product name and float array to store product price. This approach definitely achieves your goals, but try to consider these things too. What if you wanted to add more products than 20, what if you want to add more information on products like stock, discount, tax etc? It will become difficult to differentiate these variables with other variables declared for calculation etc.

To solve this problem C language has a unique data type called Structure. C structure is nothing but collection of different related data types. If we are using C structure then we are combining different related data types in one group so that we can use and manage those variables easily. Here related data type means, a structure holding information about book will contains variable and array related to book. 

Syntax for C Structure declaration

struct structure_name
{
data type member1;
data type member2;


};

Example:

struct products
{
char name[20];
int stock;
float price;
};

So structure declaration begins with struct keyword and with a space we need to provide a structure name. Within open and closed curly braces we can declare required and related variable, you can see it in our example structure declaration. And most important point to remember in case of C structure is that it ends with semicolon (;).

Let’s have a complete example of structure in C language.

Example of C structure

#include<stdio.h>
#include<conio.h>

struct product
	{
	char name[30];
	int stock;
	float price, dis;
	};

void main()
{

	 struct product p1 ={"Apple iPod Touch 32GB", 35,298.56, 2.32};
	 clrscr();
	 printf("Name=%s,\nStock=%d,\nPrice=$%.2f,\nDiscount=%.2f%.", p1.name, p1.stock, p1.price,p1.dis);
	 getch();
}

Code Explanation

So line no.4-9 declares a C structure named “product”, this structure contains four variables to store different information about product. In the beginning there is a character array (char name[30]) which stores name of the product, next we have integer variable (int stock) to store stock of product and last two variable are float type (float price, discount) to product price & discount on product respectively.

Guys we just declared product structure and now we have to use it in main(). Line no. 14 declares a product type variable p1. Here product type variable means, in our C program product is a structure and to use that structure we need to create its variable. Declaring a product structure variable is simple just use following syntax:

struct structure_name variable_name;

Remember struct is a C keyword, “structure_name” is name of structure you used while declaring a C structure (in above C program its product) and “variable_name” could be any name of your choice (in above C program its p1) but standard naming convention applies.

Along with declaring C structure variable p1 we have also initialized it and to initialize C structure you need to assign values in proper order. Proper order means assign value in the order they are declared in structure. For example, in our product structure we declare variable in following orders:

char name[30];
int stock;
float price, discount;

So for this structure proper order will be:

char name[30];
int stock;
float price;
float discount;

You don’t need to rewrite your structure, you just need to keep it in mind that structure variable initialization should be performed in orderly manner (top – bottom and left – right manner) otherwise it will show error or you may get strange output.

So in above program we have initialized p1 variable in following way:

struct product p1 ={"Apple iPod Touch 32GB", 35, 298.56, 2.32}; means

struct product p1 ={char name[30], int stock, float price, float discount}; //this line of code is only assumption.

Next in line no. 16 we just printed the values stores in product structure. You cannot print values stored in product structure member variable (like name, stock etc.) directly, you have to link member variable with structure variable and you can do this using (.) dot operator. For example: character array name is unknown to main() because it is declared in structure product, so to access member variable we will follow the following syntax:

structure_variable.member_variable;

Example:

p1.name;

We can rewrite printf("Name=%s,\nStock=%d,\nPrice=$%.2f,\nDiscount=%.2f%.", p1.name, p1.stock, p1.price,p1.discount); in the following manner:

printf(“Name = %s”,p1.name);
printf(“Stock = %d”,p1.stock);
printf(“Price = $%.2f”,p1.price);
printf(“Stock = %.2f”,p1.discount);

Here is full working code sample of C Structure.

#include<stdio.h>
#include<conio.h>

struct product
	{
	char name[30];
	int stock;
	float price, discount;
	};

void main()
{

	 struct product p1 ={"Apple iPod Touch 32GB", 35,298.56, 2.32};
	 clrscr();
	 printf("Name    = %s\n",p1.name);
	 printf("Stock   = %d\n",p1.stock);
	 printf("Price   = %.2f\n",p1.price);
	 printf("Discount= %.2f\n",p1.discount);
	 getch();
}

I hope this will help you understand C Structure, we will see more C structure example code in my next tutorial. If you have any question regarding this topic please drop comment. Thanks for dropping in.

Questions & Answers

    © 2010 RAJKISHOR SAHU

    Comments

      0 of 8192 characters used
      Post Comment
      • profile image

        Naveen 

        8 months ago

        What are the advantages of structures in C

      • profile image

        Bindeshwar Singh Kushwaha 

        15 months ago

        Very useful post thanks for writing.

      • profile image

        Sofie Norberts 

        6 years ago

        great Structure tutorials

      • rajkishor09 profile imageAUTHOR

        RAJKISHOR SAHU 

        7 years ago from Bangalore, Karnataka, INDIA

      • profile image

        rachel domingo 

        7 years ago

        how can i create a program .. f i am a begginer?can u help me to develop my knowledge in programming/

      • profile image

        shab 

        7 years ago

        great

      • profile image

        manzoor samejo 

        7 years ago

        arrays

      • profile image

        sukhraj johal(moga) 

        7 years ago

        thnks for this tutorial...................sir.thnks 1 again....................

      • Java Programs profile image

        Java Programs 

        7 years ago from India

        Wow ... very much simple and readable ... i have bookmarked it for the future reference also. Great job ... keep the good work up ....

      • profile image

        minahilpari26@gmail.com 

        7 years ago

        fit

        suprereb defination of c language

      • profile image

        kaifi 

        7 years ago

        great

      • profile image

        suvarna 

        7 years ago

        i want variable explanation

      • profile image

        MANINDER SINGH 

        7 years ago

        NIC 1

      • profile image

        akhil 

        7 years ago

        its really great nd gud to have dis helped me a lot......

      • profile image

        HP C4092A Cartridge 

        8 years ago

        Nice tutorials, i bookmarked it for future references. I will also recommend this to my friends.

      • profile image

        sree 

        8 years ago

        greate ....i never seen before like this simple tutorial....

      • profile image

        njumudeen 

        8 years ago

        Thnks for this tutorial,visit

      • sambaran08 profile image

        sambaran08 

        8 years ago from India

        Thnks for this tutorial,visit

        https://hubpages.com/technology/Cnet

        and follow me

      • profile image

        sonia 

        8 years ago

        nice tutorial.thnx for such tutorial.

      • profile image

        Pawan kumar 

        8 years ago

        i am very like you

      • biggig profile image

        biggig 

        9 years ago from India

        that was just great.. but still..i would love if you recommend a book for me... i have been reading let us c but seems it still not a able to understand it

      • rajkishor09 profile imageAUTHOR

        RAJKISHOR SAHU 

        9 years ago from Bangalore, Karnataka, INDIA

        yes a structure can have more than one structure variable just like we create variable of int, char, float etc.

        More advance topic on structure is here: https://hubpages.com/technology/Arrays-of-Structur...

      • profile image

        madhura 

        9 years ago

        can a structure have more than one structure variable

      working

      This website uses cookies

      As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

      For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://owlcation.com/privacy-policy#gdpr

      Show Details
      Necessary
      HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
      LoginThis is necessary to sign in to the HubPages Service.
      Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
      AkismetThis is used to detect comment spam. (Privacy Policy)
      HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
      HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
      Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
      CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
      Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
      Features
      Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
      Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
      Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
      Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
      Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
      VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
      PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
      Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
      MavenThis supports the Maven widget and search functionality. (Privacy Policy)
      Marketing
      Google AdSenseThis is an ad network. (Privacy Policy)
      Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
      Index ExchangeThis is an ad network. (Privacy Policy)
      SovrnThis is an ad network. (Privacy Policy)
      Facebook AdsThis is an ad network. (Privacy Policy)
      Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
      AppNexusThis is an ad network. (Privacy Policy)
      OpenxThis is an ad network. (Privacy Policy)
      Rubicon ProjectThis is an ad network. (Privacy Policy)
      TripleLiftThis is an ad network. (Privacy Policy)
      Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
      Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
      Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
      Statistics
      Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
      ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
      Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
      ClickscoThis is a data management platform studying reader behavior (Privacy Policy)