What is structure and how to define structure

Description

We can combine variables into a single package called a structure. Structures are declared by using the struct keyword.

Syntax


struct sampleName//from   w  ww. j  a  va2  s . c  o  m
{
    int a;
    char b;
}

This structure is named sampleName. It contains two variables: an integer named a and a character named b.

Structure variable

The above command only creates the structure type. It doesn't declare any variables.

The following line declares a structure variable named s1.

struct sample s1;

Items within the structure are referred to by using dot notation.

printf("Character 1 is %s\n",g1.name);

Example


#include <stdio.h>
//from   w  ww. ja v  a2 s .  com
struct student
{
    char *name;
    float marks;
}   student1, student2;

int main ( )
{
    struct student student3;

    student1.name = "Tom";
    student2.marks = 99.9;
    printf (" Name is %s \n", student1.name);
    printf (" Marks are %f \n", student2.marks);
}

The code above generates the following result.





















Home »
  C Language »
    Language Advanced »




File
Function definition
String
Pointer
Structure
Preprocessing