C Structures

Structures are similar to arrays, however, arrays can hold data elements of smae kind whereas structures allow grouping of different data types into a single object. Structures are user-defined data types and is defined using the struct keyword.

Structures in C can hold only data members but in C++, structures can hold both data members and member functions. Structures do not follow Object Oriented Programming (OOP). This problem is solved in C++ using classes.

Syntax

struct tag {
    dataType var1;  //member definition
    dataType var2;
    //more member definitions
}structureVariable(s);

Accessing Data Members of a Structure variable

Data members can be accessed using Member selection via object name (.) as well Member selection via pointers (->). The following code explain the structures in detail.

Code

#include<stdio.h>
#include<string.h> 

struct Student{
    char name[50];
    int roll;
};
 
int main(void)
{
    struct Student student1;
    struct Student student2;
    
    strcpy(student1.name,"Charlie");
    student1.roll = 1;
    strcpy(student2.name,"Olivia");
    student2.roll = 2;
    
    //Accessing student1 details using Member selection via object name 
    printf("Student 1 Name: %s\n",student1.name);
    printf("Student 1 Roll No.: %d\n",student1.roll);
    
    //Creating a reference to student2
    struct Student *ref_student2 = &student2;
    
    //Accessing student2 details using Member selection via pointers 
    printf("Student 2 Name: %s\n",ref_student2->name);
    printf("Student 2 Roll No.: %d\n",ref_student2->roll);
    
    return 0;
}

Output

Student 1 Name: Charlie
Student 1 Roll No.: 1
Student 2 Name: Olivia
Student 2 Roll No.: 2

Structures are also used to create bit fields. Bit Fields will be discussed later on in the course.

Trending

C Programming

Remember to follow community guidelines and don't go off topic.