Struct

Posted

in

by

Variables are used for storage of individual data elements. But what if we want to group different data element and use them as a individual element.

//Example 1
#include <stdio.h>
struct tag_name {
int x;
char y;
float z;
}element1;

int main() {
struct tag_name element2;

element1.x = 1;
element1.y = 'a';
element1.z = 3.14;

element2.x = eletment1.x;
element2.y = eletment1.y;
element2.z = eletment1.z;

printf("element 1\nx = %d \ty = %c \tz= %f\nelement 2\nx = %d \ty = %c \tz= %f\n", element1.x,element1.y,element1.z,element2.x,element2.y,element2.z);
return 0;
}
Struct example 1 Code Output
Struct example 1 Code Output

Nesting Struct is a way of creating more complex data structure.

// Example 2
#include <stdio.h>

typedef struct {
int x;
char y;
} point;

int main() {
point p1, *ptPtr;

p1.x = 9;
p1.y = 'x';

printf("p1.x = %d\n",p1.x);
printf("p1.y = %c\n",p1.y);

struct line {
point pt1;
point pt2;
};

struct line l1, *l1Ptr;

l1Ptr = &l1;
ptPtr = &l1.pt1;

l1.pt1.x = 44;
l1.pt1.y = 'r';

printf("l1.pt1.x = %d\n",l1.pt1.x);
printf("l1.pt1.y = %c\n",l1.pt1.y);

printf("l1.pt1.x = %d\n",l1Ptr->pt1.x);
printf("l1.pt1.y = %c\n",ptPtr->y);


return 0;
}


Example 2 output

Comments

Leave a Reply

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