Logo

Navigation
  • Home
  • Services
    • ERP Solutions
    • Implementation Solutions
    • Support and Maintenance Solutions
    • Custom Solutions
    • Upgrade Solutions
    • Training and Mentoring
    • Web Solutions
    • Production Support
    • Architecture Designing
    • Independent Validation and Testing Services
    • Infrastructure Management
  • Expertise
    • Microsoft Development Expertise
    • Mobile Development
    • SQL Server Database and BI
    • SAP BI, SAP Hana, SAP BO
    • Oracle and BI
    • Oracle RAC
  • Technical Training
    • Learn Data Management
      • Business Intelligence
      • Data Mining
      • Data Modeling
      • Data Warehousing
      • Disaster Recovery
    • Learn Concepts
      • Application Development
      • Client Server
      • Cloud Computing Tutorials
      • Cluster Computing
      • CRM Tutorial
      • EDI Tutorials
      • ERP Tutorials
      • NLP
      • OOPS
      • Concepts
      • SOA Tutorial
      • Supply Chain
      • Technology Trends
      • UML
      • Virtualization
      • Web 2.0
    • Learn Java
      • JavaScript Tutorial
      • JSP Tutorials
      • J2EE
    • Learn Microsoft
      • MSAS
      • ASP.NET
      • ASP.NET 2.0
      • C Sharp
      • MS Project Training
      • Silverlight
      • SQL Server 2005
      • VB.NET 2005
    • Learn Networking
      • Networking
      • Wireless
    • Learn Oracle
      • Oracle 10g
      • PL/SQL
      • Oracle 11g Tutorials
      • Oracle 9i
      • Oracle Apps
    • Learn Programming
      • Ajax Tutorial
      • C Language
      • C++ Tutorials
      • CSS Tutorial
      • CSS3 Tutorial
      • JavaScript Tutorial
      • jQuery Tutorial
      • MainFrame
      • PHP Tutorial
      • VBScript Tutorial
      • XML Tutorial
    • Learn Software Testing
      • Software Testing Types
      • SQA
      • Testing
  • Career Training
    • Career Improvement
      • Career Articles
      • Certification Articles
      • Conflict Management
      • Core Skills
      • Decision Making
      • Entrepreneurship
      • Goal Setting
      • Life Skills
      • Performance Development
      • Personal Excellence
      • Personality Development
      • Problem Solving
      • Relationship Management
      • Self Confidence
      • Self Supervision
      • Social Networking
      • Strategic Planning
      • Time Management
    • Education Help
      • Career Tracks
      • Essay Writing
      • Internship Tips
      • Online Education
      • Scholarships
      • Student Loans
    • Managerial Skills
      • Business Communication
      • Business Networking
      • Facilitator Skills
      • Managing Change
      • Marketing Management
      • Meeting Management
      • Process Management
      • Project Management
      • Project Management Life Cycle
      • Project Management Process
      • Project Risk Management
      • Relationship Management
      • Task Management
      • Team Building
      • Virtual Team Management
    • Essential Life Skills
      • Anger Management
      • Anxiety Management
      • Attitude Development
      • Coaching and Mentoring
      • Emotional Intelligence
      • Stress Management
      • Positive Thinking
    • Communication Skills
      • Conversation Skills
      • Cross Culture Competence
      • English Vocabulary
      • Listening Skills
      • Public Speaking Skills
      • Questioning Skills
    • Soft Skills
      • Assertive Skills
      • Influence Skills
      • Leadership Skills
      • Memory Skills
      • People Skills
      • Presentation Skills
    • Finding a Job
      • Etiquette Tips
      • Group Discussions
      • HR Interviews
      • Interview Notes
      • Job Search Tips
      • Resume Tips
      • Sample Resumes
 

C Programming – Structures and Unions

By Brian Moriya | on May 25, 2006 |
C Language

In this tutorial you will learn about C Programming – Structures and Unions, initializing structure, assigning values to members, functions and structures, passing structure to functions, passing entire function to functions, arrays of structure, structure within a structure and union.

Structures are slightly different from the variable types you have been using till now. Structures are data types by themselves. When you define a structure or union, you are creating a custom data type.

Structures

Structures in C are used to encapsulate, or group together different data into one object. You can define a Structure as shown below:

  1. 	struct object {
  2. 	  char id[20];
  3. 	  int xpos;
  4. 	  int ypos;
  5. 	};

Structures can group data of different types as you can see in the example of a game object for a video game. The variables you declare inside the structure are called data members.

Initializing a Structure

Structure members can be initialized when you declare a variable of your structure:

  1. 	struct object player1 = {“player1”, 0, 0};

The above declaration will create a struct object called player1 with an id equal to “player1”, xpos equal to 0, and ypos equal to 0.

To access the members of a structure, you use the “.” (scope resolution) operator. Shown below is an example of how you can accomplish initialization by assigning values using the scope resolution operator:

  1. 	struct object player1;
  2. 	player1.id = “player1”;
  3. 	player1.xpos = 0;
  4. 	player1.ypos = 0;

Functions and Structures

Since structures are of custom data types, functions can return structures and also take them as arguments. Keep in mind that when you do this, you are making a copy of the structure and all it’s members so it can be quite memory intensive.

To return a structure from a function declare the function to be of the structure type you want to return. In our case a function to initialize our object structure might look like this:

  1. 	struct object createobj(char id[], int xpos, int ypos) {
  2. 	  struct object newobj;
  3.  
  4. 	  strcpy(newobj.id, name);
  5. 	  newobj.xpos = xpos;
  6. 	  newobj.ypos = ypos;
  7.  
  8. 	  return newobj;
  9. 	}

Pass Structure to a Function

Let us now learn to pass a structure to a function.  As an example let us use a function that prints members of the structure passed to it:

  1. 	void printobj(struct object obj) {
  2. 	  printf(“name: %s, ”, obj.id);
  3. 	  printf(“x position: %d, ”, obj.xpos);
  4. 	  printf(“y position: %d”, obj.ypos);
  5. 	  printf(“\n”);
  6. 	}

For completeness we shall include the full source of the above examples so you may see how it all fits together.

object1.c:

  1. 	 #include <stdio.h>
  2. 	 #include <stdlib.h>
  3.  
  4. 	struct object {
  5. 	  char id[20];
  6. 	  int xpos;
  7. 	  int ypos;
  8. 	};
  9.  
  10. 	struct object createobj(char id[], int xpos, int ypos);
  11.  
  12. 	void printobj(struct object obj);
  13.  
  14. 	void main() {
  15.  
  16. 	  struct object player1 = createobj("player1", 0, 0);
  17. 	  struct object enemy1 = createobj("enemy1", 2, 3);
  18.  
  19. 	  printobj(player1);
  20. 	  printobj(enemy1);
  21. 	}
  22.  
  23. 	struct object createobj(char id[], int xpos, int ypos) {
  24. 	  struct object newobj;
  25. 	  strcpy(newobj.id, id);
  26. 	  newobj.xpos = xpos;
  27. 	  newobj.ypos = ypos;
  28. 	  return newobj;
  29. 	}
  30.  
  31. 	void printobj(struct object obj) {
  32. 	  printf("name: %s, ", obj.id);
  33. 	  printf("x position: %d, ", obj.xpos);
  34. 	  printf("y position: %d", obj.ypos);
  35. 	  printf("\n");
  36. 	}

Here is what the output looks like:

Arrays of Structure

Since structures are data types that are especially useful for creating collection items, why not make a collection of them using an array? Let us now modify our above example object1.c to use an array of structures rather than individual ones.

object2.c:

  1. 	 #include <stdio.h>
  2. 	 #include <stdlib.h>
  3.  
  4. 	struct object {
  5. 	  char id[20];
  6. 	  int xpos;
  7. 	  int ypos;
  8. 	};
  9.  
  10. 	struct object createobj(char id[], int xpos, int ypos);
  11.  
  12. 	void printobj(struct object obj);
  13.  
  14. 	void main() {
  15.  
  16. 	  int i;
  17. 	  struct object gameobjs[2];
  18. 	  gameobjs[0] = createobj("player1", 0, 0);
  19. 	  gameobjs[1] = createobj("enemy1", 2, 3);
  20.  
  21. 	  for (i = 0; i < 2; i++)
  22. 	    printobj(gameobjs[i]);
  23.  
  24. 	  //update enemy1 position
  25. 	  gameobjs[1].xpos = 1;
  26. 	  gameobjs[1].ypos = 2;
  27.  
  28. 	  for (i = 0; i < 2; i++)
  29. 	    printobj(gameobjs[i]);
  30. 	}
  31.  
  32. 	struct object createobj(char id[], int xpos, int ypos) {
  33. 	  struct object newobj;
  34. 	  strcpy(newobj.id, id);
  35. 	  newobj.xpos = xpos;
  36. 	  newobj.ypos = ypos;
  37. 	  return newobj;
  38. 	}
  39.  
  40. 	void printobj(struct object obj) {
  41. 	  printf("name: %s, ", obj.id);
  42. 	  printf("x position: %d, ", obj.xpos);
  43. 	  printf("y position: %d", obj.ypos);
  44. 	  printf("\n");
  45. 	}

We create an array of structures called gamobjs and use the createobj function to initilize it’s elements. You can observer that there is not much difference between the two programs. We added an update for the enemy1’s position to show how to access a structure’s members when it is an element within an array.

Here is the output for this version:

Structure within a Structure

Structures may even have structures as members. Imagine our x, y coordinate pair is a structure called coordinates. We can redeclare our object structure as follows:

  1. 	struct object {
  2. 	  char id[20];
  3. 	  struct coordinates loc;
  4. 	};

You can still initialize these by using nested braces, like so:

  1. 	struct object player1 = {“player1”, {0, 0}};

To access or set members of the above internal structure you would do like this:

  1. 	struct object player1;
  2. 	player1.id = “player1”;
  3. 	player1.loc.xpos = 0;
  4. 	player1.loc.ypos = 0;

You simply add one more level of scope resolution.

Unions

Unions and Structures are identical in all ways, except for one very important aspect. Only one element in the union may have a value set at any given time. Everything we have shown you for structures will work for unions, except for setting more than one of its members at a time. Unions are mainly used to conserve memory. While each member within a structure is assigned its own unique storage area, the members that compose a union share the common storage area within the memory. Unions are useful for application involving multiple members where values are not assigned to all the members at any one time.

Let us modify our structure object from above so that it has a union for indicating dead or alive in it:

  1. 	struct object {
  2. 	  char id[20];
  3. 	  struct coordinates loc;
  4. 	  union deadoralive {
  5. 	    int alive;
  6. 	    int dead;
  7. 	  }
  8. 	};

Only dead or alive can be set to anything at any one time. You can get to it the same as with a structure inside a structure as we learned in the last section.

« « C Programming – Functions (Part-I)
C Programming – Pointers » »

Author Description

Avatar

Ads

Free Training

RSSSubscribe 417 Followers
Ads
  • Popular
  • Recent
  • C Programming – File management in C

    May 31, 2006 - 0 Comment
  • C Programming – Managing Input and Output Operations

    March 30, 2006 - 0 Comment
  • C Language – The Preprocessor

    May 31, 2006 - 0 Comment
  • C Programming – Decision Making – Branching

    April 4, 2006 - 0 Comment
  • Call by Value and Call by Reference

    July 6, 2006 - 0 Comment
  • C Programming – Decision Making – Looping

    April 4, 2006 - 0 Comment
  • Concept of Pixel in C Graphics

    July 11, 2006 - 0 Comment
  • C Programming – Arrays

    April 13, 2006 - 0 Comment
  • TSR in C – An Introduction

    July 11, 2006 - 0 Comment
  • C Programming – Handling of Character String

    April 17, 2006 - 0 Comment
  • C Programming – Data Types : Part 2

    August 21, 2011 - 0 Comment
  • C Circular Linked Lists

    June 26, 2011 - 0 Comment
  • C Doubly Linked Lists

    June 26, 2011 - 0 Comment
  • TSR in C – An Introduction

    July 11, 2006 - 0 Comment
  • Concept of Pixel in C Graphics

    July 11, 2006 - 0 Comment
  • Call by Value and Call by Reference

    July 6, 2006 - 0 Comment
  • C Language – The Preprocessor

    May 31, 2006 - 0 Comment
  • C Programming – File management in C

    May 31, 2006 - 0 Comment
  • C Programming – Linked Lists

    May 29, 2006 - 0 Comment
  • C Programming – Dynamic Memory allocation

    May 29, 2006 - 0 Comment

Exforsys e-Newsletter

ebook
 

Related Articles

  • C Programming – Data Types : Part 2
  • C Circular Linked Lists
  • C Doubly Linked Lists
  • TSR in C – An Introduction
  • Concept of Pixel in C Graphics

Latest Articles

  • Project Management Techniques
  • Product Development Best Practices
  • Importance of Quality Data Management
  • How to Maximize Quality Assurance
  • Utilizing Effective Quality Assurance Strategies
  • Sitemap
  • Privacy Policy
  • DMCA
  • Trademark Information
  • Contact Us
© 2021. All Rights Reserved.IT Training and Consulting
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.Accept Reject Read More
Privacy & Cookies Policy
Necessary Always Enabled