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

구조 변수를 비교하는 C 프로그램

<시간/>

C 프로그래밍 언어에서 구조는 단일 이름으로 함께 그룹화되는 다양한 데이터 유형 변수의 모음입니다.

구조 선언 및 초기화

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

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

여기,

  • 구조체는 키워드입니다.
  • tagname은 구조의 이름을 지정합니다.
  • member1, member2는 구조를 구성하는 데이터 항목을 지정합니다.

예를 들어,

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

구조 변수

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

첫 번째 방법

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

두 번째 방법

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

세 번째 방법

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

구조 초기화 및 액세스

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

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

첫 번째 방법

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

두 번째 방법

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

멤버 연산자를 사용한 세 번째 방법

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

예시

다음은 구조 변수의 비교를 위한 C 프로그램입니다 -

struct class{
   int number;
   char name[20];
   float marks;
};
main(){
   int x;
   struct class student1 = {001,"Hari",172.50};
   struct class student2 = {002,"Bobby", 167.00};
   struct class student3;
   student3 = student2;
   x = ((student3.number == student2.number) &&
   (student3.marks == student2.marks)) ? 1 : 0;
   if(x == 1){
      printf("\nstudent2 and student3 are same\n\n");
      printf("%d %s %f\n", student3.number,
      student3.name,
      student3.marks);
   }
   else
   printf("\nstudent2 and student3 are different\n\n");
}

출력

위의 프로그램이 실행되면 다음과 같은 출력을 생성합니다 -

student2 and student3 are same
2 Bobby 167.000000