Weird Structure Concepts in C Programming - dummies

Weird Structure Concepts in C Programming

By Dan Gookin

Structures are perhaps the weirdest type of variable in the C programming language. The two steps required to create them are unusual, but the dot method of referencing a structure’s member always seems to throw off beginning programmers. If you think that, beyond those two issues, structures couldn’t get any odder, you’re sorely mistaken.

How to put structures within structures in C programming

It’s true that a structure holds C language variables. It’s also true that a structure is a C language variable. Therefore, it follows that a structure can hold another structure as a member. Don’t let this type of odd thinking confuse you. Instead, witness the example shown in A Nested Structure.

A NESTED STRUCTURE

#include <stdio.h>
#include <string.h>
int main()
{
 struct date
 {
 int month;
 int day;
 int year;
 };
 struct human
 {
 char name[45];
 struct date birthday;
 };
 struct human president;
 strcpy(president.name,"George Washington");
 president.birthday.month = 2;
 president.birthday.day = 22;
 president.birthday.year = 1732;
 printf("%s was born on %d/%d/%dn",
 president.name,
 president.birthday.month,
 president.birthday.day,
 president.birthday.year);
 return(0);
}

A Nested Structure declares two structure types: date at Line 6 and human at Line 12. Within the human structure’s declaration, at Line 15 you see the date structure variable birthday declared. That’s effectively how one structure is born inside another.

Line 17 creates a human structure variable, president. The rest of the code fills that structure’s members with data. The method for accessing a nested structure’s members is shown in Lines 20 through 22.

The structure’s variable names are used; not the name that’s used to declare the structure.

Exercise 1: Type the source code from A Nested Structure into your editor. Build and run the program.

Exercise 2: Replace the name member in the human structure with a nested structure. Name that structure id and have it contain two members, char arrays, first and last, for storing an individual’s first and last names. If you do everything correctly, the reference to the president’s name will be the variables president.name.first and president.name.last. Be sure to assign values to these variables in your code and display the results.

How to pass a structure to a function in C programming

As a type of variable, it’s entirely possible for a function to eat a structure and cough it up. However, this situation requires that the structure be declared as a global variable. That’s because if you declare a structure within a function, and main() is a function, the definition is available only in that function.

Therefore, the declaration must be made globally so that it’s available to all functions in the code.