문제
구조를 정의하고 멤버 변수의 크기와 오프셋을 표시하는 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); 데이터 멤버로 구조를 선언하고 오프셋 값과 구조 크기를 인쇄해 보세요.
프로그램
#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 'a' is :%d\n",sizeof(t1.a));
printf("the size 'b' is :%d\n",sizeof(t1.b));
printf("the size 'c' is :%d\n",sizeof(t1.c));
printf("the size 'd' is :%d\n",sizeof(t1.d));
printf("the size 'e' is :%d\n",sizeof(t1.e));
printf("the offset 'a' is :%d\n",offsetof(struct tutorial,a));
printf("the offset 'b' is :%d\n",offsetof(struct tutorial,b));
printf("the offset 'c' is :%d\n",offsetof(struct tutorial,c));
printf("the offset 'd' is :%d\n",offsetof(struct tutorial,d));
printf("the offset 'e' is :%d\n\n",offsetof(struct tutorial,e));
printf("size of the structure tutorial is :%d",sizeof(t1));
return 0;
} 출력
the size 'a' is :4 the size 'b' is :4 the size 'c' is :4 the size 'd' is :4 the size 'e' is :8 the offset 'a' is :0 the offset 'b' is :4 the offset 'c' is :8 the offset 'd' is :12 the offset 'e' is :16 size of the structure tutorial is :24