Computer >> 컴퓨터 >  >> 프로그램 작성 >> C 프로그래밍

C 언어를 사용하여 구조에 대한 예제 프로그램 작성

<시간/>

구조는 단일 이름 구문 아래 함께 그룹화된 다양한 데이터 유형 변수의 모음입니다.

구조 선언 및 초기화

구조체 선언의 일반적인 형식은 다음과 같습니다 -

datatype member1;
struct tagname{
   datatype member2;
   datatype member n;
};

여기, 구조체 - 키워드

tagname - 구조의 이름을 지정합니다.

member1, member2 - 구조를 구성하는 데이터 항목을 지정합니다.

예시

struct book{
   int pages;
   char author [30];
   float price;
};

구조 변수

구조체 변수를 선언하는 방법에는 세 가지가 있습니다. 다음과 같습니다 -

1) struct book{
   int pages;
   char author[30];
   float price;
}b;
2) struct{
   int pages;
   char author[30];
   float price;
}b;
3) struct book{
   int pages;
   char author[30];
   float price;
};
struct book b;

구조의 초기화 및 액세스

  • 멤버와 구조체 변수 간의 연결은 멤버 연산자(또는) 점 연산자를 사용하여 설정됩니다.

  • 초기화는 다음과 같은 방법으로 할 수 있습니다 -

방법 1

struct book{
   int pages;
   char author[30];
   float price;
} b = {100, “balu", 325.75};

방법 2

struct book{
   int pages;
   char author[30];
   float price;
};
struct book b = {100, “balu", 325.75};

방법 3(멤버 연산자 사용)

struct book{
   int pages;
   char author[30];
   float price;
} ;
struct book b;
   b. pages = 100;
   strcpy (b.author, “balu");
   b.price = 325.75;

방법 4(scanf 사용 기능)

struct book{
   int pages;
   char author[30];
   float price;
} ;
struct book b;
   scanf (“%d", &b.pages);
   scanf (“%s", b.author);
   scanf (“%f", &b. price);

아래와 같이 main 메소드에서 위 구조 중 하나의 내용을 인쇄할 수 있습니다. -

main ( ){
   struct book b;
   clrscr ( );
   printf ( "enter no of pages, author, price of book");
   scanf ("%d%s%f", &b.pages, b.author, &b.price);
   printf("Details of book are");
   printf("pages =%d, author = %s, price = %f", b.pages, b.author, b.price);
   getch();
}

예시

다음은 구조의 또 다른 예입니다 -

#include<stdio.h>
struct aaa{
   struct aaa *prev;
   int i;
   struct aaa *next;
};
main(){
   struct aaa abc,def,ghi,jkl;
   int x=100;
   abc.i=0;
   abc.prev=&jkl;
   abc.next=&def;
   def.i=1;
   def.prev=&abc;
   def.next=&ghi;
   ghi.i=2;ghi.prev=&def;
   ghi.next=&jkl;
   jkl.i=3;
   jkl.prev=&ghi;
   jkl.next=&abc;
   x=abc.next->next->prev->next->i;
   printf("%d",x);
}

출력

2