article

Basics of C/C++ Part 7: Structures

Email
Submitted on: 1/1/2015 7:39:00 AM
By: Alexander of CProgramming.com (from psc cd)  
Level: Intermediate
User Rating: By 6 Users
Compatibility: C, C++ (general)
Views: 694
 
     Welcome to the seventh lesson. This is my first lesson that I will explain classes. However, I will explain more about structures, because they can be useful, and they are a good way to get a feel for how a class works. What are structures? They are a way to store more than one data-type under the same name.

 
				

Fore example:

#include //For strcpy
struct database
{
int age;
char name[20];
float salary;
};

void main()
{
database employee;
employee.age=22;
strcpy(employee.name, "Joe");
employee.salary= 12000.21;

}

Don't worry about the name[20]. That is just an array. It can hold more than one character all called under the same name. They are used like strings. I will do my next lesson on arrays, I promise, because they are very important. The struct database declares that database has three variables in it, age, name, and salary.

Eventually, you can use database like a variable type like int. You can create an employee with the database type like I did above. Then, to modify it you call everything with the employee. in front of it. You can also return structures from functions by defining their return type as a structure type. Example:

struct database fn();

You can make arrays of structures as well. I will show you how to do this in lesson 8.

That will be up in a few days. I suppose I should explain unions a little bit. They are like structures except that all the variables share the same memory. When a union is declared the compiler allocates enough memory for the largest data-type in the union.

To access the union you use the . like in structures. Also, if you are accessing the union of structure through a pointer use the -> operator. for example, database->employee . The most useful thing about unions is that you can manipulate the bytes of the data-types. You might want to see what you can do if you understand that sort of stuff. Personally, I have never used a union.


Other 10 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Intermediate category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.