C Programming/Structure Datatype

From Chorke Wiki
Revision as of 06:14, 5 February 2018 by Shahed (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
  1. A structure in C is a collection of items of different types. Structure may be consider as a record like Pascal or a class in Java without methods.
  2. Structures, or structs, are very useful in creating data structures larger and more complex
  3. Simply group various built-in data types into a structure.
  4. Object concepts was derived from Structure concept.
//main.c
#include <stdio.h>

struct student {
    char  firstName[20];
    char  lastName[20];
    char  SSN[10];
    float gpa;
};

int main(void)
{
    struct student student_a;

    strcpy(student_a.firstName, "Deo");
    strcpy(student_a.lastName,  "Dum");
    strcpy(student_a.SSN,  "2333234" );
    student_a.gpa = 2009.20;

    printf( "First Name: %s\n", student_a.firstName );
    printf( "Last Name : %s\n", student_a.lastName );
    printf( "SNN       : %s\n", student_a.SSN );
    printf( "GPA       : %f\n", student_a.gpa );

    return 0;
}

Typedef Keyword

This is an easier way to define structs and could be use a user defined type. Need not declare each time of use.

//main.c
#include <stdio.h>

typedef struct{
    char  firstName[20];
    char  lastName[20];
    char  SSN[10];
    float gpa;
}student;

int main(void)
{
    student student_a;

    strcpy(student_a.firstName, "Deo");
    strcpy(student_a.lastName,  "Dum");
    strcpy(student_a.SSN,  "2333234" );
    student_a.gpa = 2009.20;

    printf( "First Name: %s\n", student_a.firstName );
    printf( "Last Name : %s\n", student_a.lastName );
    printf( "SNN       : %s\n", student_a.SSN );
    printf( "GPA       : %f\n", student_a.gpa );

    return 0;
}

Unions Datatype

Unions are declared in the same fashion as structs, but have a fundamental difference. Only one item within the union can be used at any time, because the memory allocated for each item inside the union is in a shared memory location.

union Shape {
    int circle;
    int triangle;
    int oval;
};