>  기사  >  백엔드 개발  >  구조체 멤버의 크기와 오프셋을 표시하는 C 프로그램을 작성하세요.

구조체 멤버의 크기와 오프셋을 표시하는 C 프로그램을 작성하세요.

WBOY
WBOY앞으로
2023-08-29 20:09:19670검색

구조체 멤버의 크기와 오프셋을 표시하는 C 프로그램을 작성하세요.

Problem

구조를 정의하고 멤버 변수의 크기와 오프셋을 표시하는 C 프로그램을 작성하세요.

Structure - 서로 다른 데이터 유형의 변수를 하나의 이름으로 그룹화한 모음입니다.

구조 선언의 일반적인 형식

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

여기서 struct - 키워드

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);

데이터 멤버를 사용하여 구조를 선언하고 오프셋 인쇄를 시도합니다. 값과 구조의 크기.

Program

실시간 시연

#include<stdio.h>
#include<stddef.h>
struct tutorial{
   int a;
   int b;
   char c[4];
   float d;
   double e;
};
int main(){
   struct tutorial t1;
   printf("the size &#39;a&#39; is :%d</p><p>",sizeof(t1.a));
   printf("the size &#39;b&#39; is :%d</p><p>",sizeof(t1.b));
   printf("the size &#39;c&#39; is :%d</p><p>",sizeof(t1.c));
   printf("the size &#39;d&#39; is :%d</p><p>",sizeof(t1.d));
   printf("the size &#39;e&#39; is :%d</p><p>",sizeof(t1.e));
   printf("the offset &#39;a&#39; is :%d</p><p>",offsetof(struct tutorial,a));
   printf("the offset &#39;b&#39; is :%d</p><p>",offsetof(struct tutorial,b));
   printf("the offset &#39;c&#39; is :%d</p><p>",offsetof(struct tutorial,c));
   printf("the offset &#39;d&#39; is :%d</p><p>",offsetof(struct tutorial,d));
   printf("the offset &#39;e&#39; is :%d</p><p></p><p>",offsetof(struct tutorial,e));
   printf("size of the structure tutorial is :%d",sizeof(t1));
   return 0;
}

Output

the size &#39;a&#39; is :4
the size &#39;b&#39; is :4
the size &#39;c&#39; is :4
the size &#39;d&#39; is :4
the size &#39;e&#39; is :8
the offset &#39;a&#39; is :0
the offset &#39;b&#39; is :4
the offset &#39;c&#39; is :8
the offset &#39;d&#39; is :12
the offset &#39;e&#39; is :16

size of the structure tutorial is :24

위 내용은 구조체 멤버의 크기와 오프셋을 표시하는 C 프로그램을 작성하세요.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제