Structure

A structure is a derived data type in C. It is used to group different data types under the same name together.

syntax:

struct structure_name{

data_type1 variable_name1;

data_type2 variable_name2;

…….

…..

};

Are you confused? you could create a structure called the customer, which contains a customer name, and customer contact number.

struct customer
{
char *name;
int number;
};

Note the semicolon; behind the last curly bracket.

you have created a new data type now called the customer. To access this data type, you have to create a variable of the type customer.

struct customer customer1;

To access the members of a structure, you must use dot(“.”) operator like this,

customer1.name = “john”;

customer1.number = 123456789;

program:

#include
struct customer
{
char *name;
int number;
};

int main()
{
struct customer customer1;
customer1.name = "John";
customer1.number = 123456789;
printf("Name: %s\n", customer1.name);
printf("Telephone number: %d\n", customer1.number);
return 0;
}

output:

Name: John

Telephone Number: 123456789

Pointers to Structs:

Sometimes it is useful to assign a pointer to a structure. Declaring pointers to structures is basically the same as declaring a normal pointer.
struct customer *customer1;
To reference, you can use the infix operator: ->.
printf(“%s\n”, customer1->name)

 

Leave a Reply

Your email address will not be published. Required fields are marked *