C is a very common programming language, and it has been around since 1975. In fact, the C language is so widely used that it is used in many operating systems, including Linux, OSX, and Android. In this article, we will discuss some basic C concepts, and how they relate to C programming.
C structures are a simple way to give a running program a discrete amount of memory. They are so simple, in fact, that many programmers today have never used a C structure, and a lot of other programmers have a difficult time understanding them.
The near future will likely see an explosion of new computing devices. So, if you are looking to get started in computer science, or are simply curious about the world of programmers, this post should be of interest. C programming is at the heart of any computer program. But, if you are unfamiliar with how to program, you might find this post a bit tricky to navigate.
The ability to combine similar data elements of the same kind into a single object is provided by arrays. However, there are instances when we need to group together similar data objects of various kinds. An inventory record for a stock item, for example, brings together the item number, price, amount in stock, reorder level, and so on. C offers a data type called structures that enables a set number of data items, potentially of various kinds, to be handled as a single object in such circumstances. It’s used to combine all relevant data into a single variable.
The Fundamentals of Structures
A structural tag is a collection of logically linked data elements that are put together under a single name. Members or fields are the data elements that make up a structure, and they may be of many kinds.
The following is a general format for defining a structure:
data type member1; data type member2;…; struct tag name
where, struct: A keyword that begins the definition of a structure. member1, member2: Set of type declarations for the member data items that make up the structure tag name: The name of the structure tag name: The name of the structure tag name: The name of the structure tag name: The name of the structure tag name: The name of the structure tag name:
As an example, the inventory record structure for a stock item might be specified as:
int itemno; float price; float quantity; int reorderlevel; struct itemno; int itemno; int itemno; int itemno; int itemno; int itemno; int itemno; int
Consider a book database with information such as the title, author, number of pages, and price. The structure may be defined as follows to store the book information:
book bank struct char title[15]; char author[10]; int pages; float price; char title[15]; char author[10]; int pages; float price; char title[15]; char author[10]; int pages
There are no variables declared in the preceding declaration. It merely specifies a format for representing information known as a template, as illustrated below:
pages integer price float struct book bank title array of 15 characters author array of 10 characters
The following diagram roughly depicts the structure of this book database.
All elements of a structure may be of the same type, as seen in the structure date definition below.
struct date int day,month,year; struct date int day,month,year; struct date int day,month,year; struct date int day
Individual members of a structure are declared.
Individual members of a structure may be any kind of data (int, float, etc. ), pointers, arrays, or even other structures. Individual members of a structure may be any kind of data (int, float, etc. ), pointers, arrays, or even other structures.
Individual members of the structure declaration cannot be initialized.
Variables in the structure
A structure definition creates a new type, which may then be declared in the following ways: In the declaration of structure: Between the right brace and the termination semicolon in the structure declaration, provide a list of variable names.
Consider the following declaration:
struct student int rollno; char subject[10]; float marks; struct student int rollno; int rollno; int rollno; int rollno; int rollno; int students 1 and 2;
defines student1 and student2 as struct student variables. The tag name student may be removed if additional structural variables are not needed, as illustrated below:
float marks; struct int rollno; char name[10]; int rollno; int rollno; int rollno; int rollno; int rollno; int rolln students 1 and 2;
The structure tag is used in this example.
Variables may also be specified to be of a certain structural type by a declaration of the form:
variable-list struct tag;
For example,
student1; student2; student3; student4; student5; student6; student7; student8; student
defines student1 and student2 to be struct student variables.
Initiation of Structure
Following the declaration of a variable with an initializer for the appropriate structure type, the variable may be initialized. Initializer provides starting values for structure components, separated by commas and enclosed in curly brackets. As a result, the following declaration:
struct date int day,month,year; struct date int day,month,year; struct date int day,month,year; struct date in independence={15,8,1947};
The structural variable independence’s member variables day, month, and year are set to 15, 8, and 1947, respectively.
Declaratory statement:
struct republic =26.1.1950; struct republic =26.1.1950; struct republic =26.1.1950; struct republic =26.
The structural variable republic’s member variables day, month, and year are set to 26, 1, and 1950, respectively. The declaration is based on the structural definition student (specified in 8.1.2).
student1=1,”Ashwini,”98.5; struct student student1=1,”Ashwini,”98.5; struct student student1=1,”Ashwini,”
The structural variable student1’s member variables rollno, name, and marks are set to 1, “Ashwini,” and 98.5, respectively. If the number of initializers in the structure is less than the number of member variables, the remaining member variables are set to zero.
As a result, the initialization:
newyear=1,1; struct date newyear=1,1;
is equivalent to:
newyear=1,1,0; struct date newyear=1,1,0;
Members of the structure may be accessed.
Individual elements of a structure can be retrieved using the dot operator(.) and the syntax is of the form:
structure-variable.member-name;
As a result, we may use the following to refer to the structural student’s name:
The assertions,
emp.day=28; emp.month=7; emp.year=1969; struct date emp; emp.day=28; emp.month=7; emp.year=1969;
Set the member variables day, month, and year in the variable emp to 28, 7, and 1969, respectively, and then run the script.
struct date today; if(today.day==1&&today.month==1) printf(“Happy New Year”);
Checks whether the values of day and month are both 1 and displays the message if they are. A structure’s elements are always stored in contiguous memory regions. It is as follows:
Here are some examples of how structures may be used:
/* Program to print the date using structure variable */ # include void main(void) { struct date { char month[15]; int day,year; }; struct date today; today.day=11; printf(“Enter Month : ”); scanf(“%[^n]”,today.month); today.year=1998; printf(“nToday’s date is %d-%s-%d n”, today.day,today.month,today.year); }
*** str.h *** struct date int month,day,year; *** str.h *** struct date int month,day,year; *** str.h *** struct date int month,day,year
/* Program to print the date using structure variable */ #include # include “str.h” void main(void) { struct date today; struct date tomorrow; static int day_month[12]= {31,28,31,30,31,30,31,31,30,31,30,31}; printf(“Enter Today’s date (dd:mm:yy): ”); scanf(“%d%d%d”,&today.day,&today.month,&today.year); if(today.day > day_month[today.month-1]) { printf(“n Invalid Date n”); exit(0); } if(today.day!=day_month[today.month-1]) { tomorrow.day=today.day+1; tomorrow.month=today.month; tomorrow.year=today.year; } else if(today.month==12) { tomorrow.day=1; tomorrow.month=1; tomorrow.year=today.year+1; } else { tomorrow.day=1; tomorrow.month= today.month+1; tomorrow.year=today.year; } printf(“n Tomorrow’s date is %d-%d-%d n”, tomorrow.day,tomorrow.month,tomorrow.year); }
The assignment operator, as well as element by element like arrays, may be used to copy one structure to another of the same kind.
Members of a structure variable’s values are allocated to members of another structure variable of the same type in this instance. The following example exemplifies this concept.
*** strdef.h *** struct date char month[5]; int day,year; struct date char month[5]; int day,year; struct date char month[5]; int day,year; struct date char month[5];
# include # include # include “strdef.h” void main /* Example – Copying a structure to another structure */ (void) today=“March”,1,98; struct date today=“March”,1,98; struct date day1,day2; strcpy(day1.month,today.month); day1.day=today.day; day1.year=today.year; /* copying entire structure to another structure */ day2=day1; printf(“n Date is percent d percent s percent d n”, today.day,today.month,today.year); printf(“n Date is percent d percent s percent d n”, day1.day
Structures and Functions
Functions may take structures as parameters. Structure names, unlike array names, which always refer to the beginning of the array, are not pointers. As a consequence, when we modify a structural parameter inside a function, the associated argument is unaffected.
Structure is sent from elements to functions:
A structure may be given as a single member or as a distinct variable to a function. Below is an example of a program that displays the contents of a structure by providing the individual components to a function.
# include < stdio.h > void main() { int emp_id; char name[25]; char department[10]; float salary; }; static struct emp1={125,”sampath”,”operator”,7500.00}; /* pass only emp_id and name to display function*/ display(emp1.emp_id,emp1.name); } /* function to display structure variables*/ display(int e_no,char *e_name) { printf(“%d%s”,e_no,e_name); }
Emp id and name have been specified as integer and character array in the structure type definition. When we use show(emp1.emp id,emp1.name) to call the method display(), we are passing the emp id and name to the function display (). It’s obvious that passing individual components will get more laborious as the number of structure elements grows, therefore passing the whole structure variable at once is a preferable option.
Functions are passed the full structure:
In case of structures having to having numerous structure elements passing these individual elements would be a tedious task. In such cases we may pass whole structure to a function as shown below:
# include int emp id; char name[25]; char department[10]; float salary; void main() static struct employee emp1=12, “sadanand”, “computer”, 7500.00; display(emp1); /*sending full employee structure*/ /*function to pass whole structure variable*/ display(emp1); (struct employee empf) empf.empid,empf.name,empf.department,empf.salary); printf(“ percent d percent s, percent s, percent f”, empf.empid,empf.name,empf.department,empf.salary);
Arrays and Structures
Arrays and structures may freely mix and match to form arrays of structures and structures containing arrays.
Structures in Arrays
Individual structures make up the components of the array of structures. When a large number of comparable records must be processed at the same time, they are frequently utilized.
For instance, data from a motor with 1000 components may be arranged in an array of structure as follows:
This line defines motor to be a 1000-element array of the struct item type.
As seen below, an array of structures may be defined in two ways. The first method is to declare:
char name[10] in struct person; struct birthday in struct date; float salary in float salary in float salary in float salary in float salary in float salary in float salary in float salary in float emprec[15];
emprec is an array of 15 person structures in this instance. The structure of type person will be included in each member of the array emprec. The person structure is made up of three parts: an array name, a salary, and a structure date. Before it may be used inside the enclosing structure, the embedded structure date must be specified. The structure tag is used in the second solution to the identical issue, as seen below.
struct person char name[10]; struct date birthday; float salary; struct person emprec[15]; struct person emprec[16]; struct person emprec[17]; struct person emprec[18]; struct person emprec[19]; struct person emprec
The program that follows demonstrates how to utilize an array of structures.
/* Example- An array of structures */ # include void main(void) { struct book { char name[15]; int pages; float price; }; struct book b[10]; int i; printf(“n Enter name, pages and price of the bookn”); /* accessing elements of array of structures */ for(i=0;i<9;i++) { scanf(“%s%d%f”,b[i].name,&b[i].pages,&b[i].price); printf(“n”); } printf(“n Name, Pages and Price of the book :n”); for(i=0;i<=9;i++) { printf(“%s %d %f”,b[i].name,b[i].pages,b[i].price); } }
Structures with Arrays
Arrays may be members of a structure. When a string has to be incorporated in a structure, this capability is often utilized. For example, the date structure may be extended to contain the names of the weekdays and months as follows:
int month; char monthname[10]; int year; struct date char weekday[10]; int day; int month; char monthname[10]; int year;
– may be used to define and initialize the structural variable ndate.
struct date ndate=”Sunday,”21,11,”November,”2004; struct date ndate=”Sunday,”21,11,”November,”2004; struct date ndate=”Sunday
The dot and array subscript operators may be used to access an element of an array stored in a structure. As a result, the statement,
printf(“ percent c”,ndate.monthname[2]); printf(“ percent c”,ndate.monthname[2]); printf(“ percent c
prints v.
Pointers and Structures
Structures Pointers
The beginning address of a structure can be accessed in the same manner as any other address, through the use of the address of (&) operator. Thus, if variable represents a structure-type variable, then:
indicates the variable’s initial address. Furthermore, we may define a structure’s pointer variable by writing:
where you should type: A data type that indicates the structure’s composition ptvar: The pointer variable’s name is
Structure Pointers is a pointer variable that holds the structure’s address. Consider the following declaration:
ndate,*ptrndate; struct date ndate,*ptrndate;
defines the variable ndate as a struct date variable and ptrndate as a pointer to a struct date variable. Consider the following illustration:
account; account customer,*pc; typedef struct int acct no; char acct type; char name[20]; float balance; date lastpayment; account; account customer,*pc; typedef struct int acct no; char acct type; char name[20]; float balance; date lastpayment; account; account customer,*pc; typedef
In this example, customer is a structure variable of type account, and pc is a pointer variable whose object is a structure of type account. The address operator (&) is applied to a structure variable to obtain the beginning address of customer. It can be assigned to pc by writing.
The structure declaration may be coupled with the variable and pointer declarations by writing
struct,*ptvar; struct,*ptvar; struct,*ptvar; struct,*ptvar; struct,*ptvar; struct,*ptvar; struct,*ptvar; struct,
Where the variable is: A variable of the structural type ptvar: A pointer variable’s name.
The following single declaration is equal to the preceding example’s two declarations.
struct int acct no; char acct type; char name[20]; float balance; date lastpayment; customer,*pc; struct int acct no; char acct type; char name[20]; float balance; date lastpayment;
Using the dot operator, the pointer variable pc may now be used to access the member variables of customer:
(*pc).acct type; (*pc).name; (*pc).no; (*pc).no; (*pc).no; (*pc).no; (*pc).no; (*pc).n
The parentheses are necessary because the dot operator(.) has higher precedence than that of the dereferencing operator(*). The members can also be accessed by using a special operator called the structure pointer or arrow operator (->).
The general form for the use of the operator -> is
printer_name->member_name;
Thus,
if pc=&customer pc->balance=(*pc).balance=customer.balance
where balance is a customer of the structure.
It’s possible to get the addresses of a structure variable’s member variables. Consider the following example:
float *ptrbal=&customer.balance;
defines ptrbal to be a floating point pointer and initializes it to point to the member variable balance within the structure variable customer. The pointer expression &customer.balance is interpreted as &(customer.balance) since, the precedence of the dot operator is higher than that of the address operator.
/* Example- structure pointers */ # include # include “str.h” struct { int acct_no; char acct_type; char *name; float balance; struct date *lastpayment; }customer, *pc = &customer; struct date PaymentDate ; void main(void) { PaymentDate.day = 26 ; PaymentDate.month = 1 ; PaymentDate.year = 1999 ; customer.acct_no=55; customer.acct_type=”A”; customer.name=”Ashwini”; customer.balance=99.99; customer.lastpayment = &PaymentDate ; printf(“Account:%dn”,pc->acct_no); printf(“Acc_Type : %c n”,pc->acct_type); printf(“Name : %s n”,pc->name); printf(“Balance : %.2f n”,pc->balance); printf(“LastPayment : %2d-%2d-%4d n”, pc->lastpayment->day,pc->lastpayment->month, pc->lastpayment->year); }
Within the second structure, the members acct_no, acct_type, name and balance are written as pointers. Thus, the value to which acct_no points can be accessed by writing either *customer.acct_no or *p->acct_no. Same in case of acct_type and balance. A string can be assigned directly to a character type pointer. Therefore, if name points to the beginning of a string, then the string can be accessed by writing either customer.name or pc->name.
Allocating Memory for a Structure Pointer
If you wish to save data, memory from the heap must be allocated for a reference to a structure, which is done using the malloc() method.
Example:
char name[20]; char address[20]; int empid; emp,*empptr; typedef struct char name[20]; char address[20]; int empid; emp,*empptr; typedef struct char name[20]; char address[20]
The following line may be used to allocate RAM for storing information about ten employees:
empptr=(emp*)malloc(10*sizeof(emp));
You may use the pointer to retrieve the information after the memory has been allocated, as shown below.
for(i=0;i<10;i++) { scanf(“%s%s%d”,empptr[i].name,empptr[i].address, & empptr[i].empid); }
Pointer-Containing Structures
Pointers may be used as member variables in a structure. For instance, consider the structure definition.
char *name; char *addr; struct location;
creates a structure location with two character pointers as member variables, name and addr. Location variables of type struct may now be created and managed as follows:
struct location att={“Ashwini”,”Boston’s Computer Institute”}; struct location ibm; ibm.name=”R&D”; ibm.addr=”Bell Labs,California”;
Getting a hold of the structure date specified in str.h:
struct person char name[20]; char *lastname; struct date birthday; float *salary; emprec; *** str1.h *** # include “str.h” struct person char name[20]; char *lastname; struct date birthday; float *salary; emprec;
*** strptr.c*** *** strptr.c*** *** strptr.c***
/* Example- structure containing pointers */ # include # include “str1.h” void main(void) { float x; struct person *ptr = &emprec; struct date *birth = &emprec.birthday; strcpy(emprec.name,”Ashwini”); emprec.lastname = ”A.”; ptr->birthday.day = 28; emprec.birthday.month = 7; birth->year = 97; x=5000; ptr->salary = &x; printf(“ *** Employee Details *** n”); printf(“Name :%s %s n”,ptr->name,ptr->lastname); printf(“Birthdate: %d:%d:%d n”,(*ptr).birthday.day, birth->month,emprec.birthday.year); printf(“Salary :%6.2f”,emprec.salary); }
Output:
*** Employee Information *** Ashwini A. is her given name. 28:7:97 is my birthday. 5000.00 per month
Allocating Memory for a Pointer-Containing Structure
When a structure has a member that is a pointer to another structure, it is not enough to allocate memory for the structure’s reference; you must also allocate memory for the member pointer.
typedef struct char* name; char* address; int empid; emp,*empptr; typedef struct char* name; char* address; int empid; typedef struct char* address; int empid; typedef struct char* address; int empi
The following software shows how to allocate memory for a pointer inside a structure. At runtime, the user may input the total number of workers and the name size.
#include #include #include void main(void) { int n,i,j; typedef struct { int empno; char *name; }emp; emp *empptr; char name[80] ; printf(“Enter total no. of employees:”); scanf(“%d”,&n); fflush(stdin); empptr = (emp *) malloc(n * sizeof(emp)); for(i = 0 ; i < n ; i++) { printf(“n Enter empno of employee (%d) :”,i+1); scanf(“%d”,&empptr[i].empno); fflush(stdin); printf(“n Enter name :”); scanf(“%[^n]”,name); fflush(stdin); empptr[i].name = (char *) malloc(strlen(name) * sizeof(char) + 1 ); strcpy(empptr[i].name, name) ; } for(i=0;i < n ; i++) { printf(“nno-%d tname-%s”,empptr[i].empno, empptr[i].name); } }
C structures are simple structures that are used in many programming languages to represent data. They are also used in data structures, although they are not the only data structure in which they are used. C structures are made up of three parts: a header, a body, and a footer. The header is the start of the structure and the footer is the end of the structure. The body is everything in between.. Read more about array of structure in c and let us know what you think.
Related Tags
- structure of c program with example
- c struct initialization
- typedef struct in c
- structure pointer in c
- structure and union in c