Loading...
Loading...
00:00:00

What Is Structure In C?

Structure is user defined data type that allow to create new data type using predefined data types. Structure is group of predefined data type. To create a structure data type we have to use struct keyword. struct keyword can be used for create a new structure data type. In C language, we cannot declare a function inside structure body.

Structure Syntax: 

// define a structure
struct structure_name
{
    // member Variables
    int x;
    int y;
    float price;
}variables_name;
// create structure variable
struct structure_name st; 

Assign And Access Value In Struture Variables

In structure variables we can access structure members using.(dot) operator and using this operator we can Assign value. here is the complete example to create a structure and assign value and access structure member variables.

#include <stdio.h>
#include <stdlib.h>

// define a structure
struct python
{
    // structure member variables
    int id;
    int duration;
    float price;
}p2;  // you can create a variable here

int main(int argc, char const *argv[])
{
    struct python p1; // create structure variable
    p1.duration = 2;  // assign value in structure member variables
    p1.id = 100;
    p1.price = 2000;
    printf("p1 course id is %d .", p1.id); // access structure member variable value using . operator
    printf("p1 course duration is %d months.", p1.duration);
    printf("p1 course price is %f rupees.", p1.price);

    return 0;
}

What Is Typedef?

In c programming, typedef keyword is used to create a new name of data type or alias of data type.

Example of typedef

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    typedef unsigned int positive_num;  // typedef for alias for "unsigned int" as positive_num
    positive_num number1 = 500;
    positive_num number2 = 8700;
    printf("The product is %d", number1 * number2);
    return 0;
}

Use Of Typedef Keyword For Structure

we can use variable for user defined data type such as structure. typedef keyword can be use for create a variable of structure data type. Here is the Example −

#include <stdio.h>
#include <stdlib.h>

// define a structure and use typedef
typedef struct python  
{
    // variable declared
    int id;
    int duration;
    float price;
}py;   //create a variable

int main(int argc, char const *argv[])
{
    py p1;  // create a variable  no need to use 'struct'
    /* 
        we can use 'typedef struct python py;'  same as above Example
    */
    p1.duration = 2;  // assign value in structure variables
    p1.id = 100;
    p1.price = 2000;
    printf("p1 course id is %d .", p1.id); // access structure variable value using . operator
    printf("p1 course duration is %d months.", p1.duration);
    printf("p1 course price is %f rupees.", p1.price);

    return 0;
}