서로 다른 데이터 타입을 갖는 자료들을 동일한 이름으로 묶어 놓은 것.
배열은 동일한 데이터 타입을 갖는 자료들을 묶어 놓은 것이므로 배열과는 다른 개념이다.
< 배열과 구조체 차이 >
int a[10]={1,2,3,4,5); // 배열형
struct a{
int num;
char name[20];
}; // 구조체형. 배열이 int형으로 전부 묶인 것과 달리 구조체는 int형, char형을 동시에 묶을 수 있다
#형식 -----
struct 구조체 이름{
멤버;
멤버;
,,};
---- 예시 ---
struct customer{
int num;
char name[20];
double point;
};
main 문에서 사용하기 위해서는 구조체를 먼저 선언해주고 이후 main문에서 구조체 변수도 선언해주어야 한다
--- 구조체 변수 선언 방식 ---
int main(){
....
struct (구조체 이름) (선언할 변수 이름) = {...};
...
};
----예시----
struct customer{
int num;
char name[20];
double point;
};
int main(){
struct customer a1={1,"kim sh", 103.99};
// custmoer 라는 이름을 가진 구조체에 대한 변수 a1을 선언해주고 a1에 대한 값을 초기화해준다.
--- 접근 방법 ---
(구조체 변수).(멤버) // .을 사용해서 접근한다
---- 예시 ---
#include <stdio.h>
struct customer{
int num;
char name[20];
double point;
};
int main(){
struct customer a1={1,"kim sh", 103.99};
printf("num=%d name=%s point=%lf\n", a1.num, a1.name, a1.point);
return 0;
}
// 구조체 변수 a1에 대한 int형, char형, double형 멤버에 접근하기 위해 .(닷)을 사용해 접근한다
구조체 형식으로 배열과 같이 여러 개를 묶을 수 있다.
struct abc{
int num;
float kor;
float eng;
float c;
};
..
int main() {
...
struct abc a[3]={
{100,90,80},
{90,90,80},
{100,100,100}};
...
};
// 구조체 변수의 멤버에 접근해서 출력해보면
a[0].num, a[0].kor, a[0].eng 는 100,90,80이 출력될 것이다
typedef struct (구조체 이름) {
...}St
# 1. struct 구조체 선언시 main 문에서 구조체 사용 예
int main () {
...
struct ( 구조체 이름) ( 구조체 변수 ) = {..};
...};
----
# 2. typedef 사용시 main 문에서 구조체 사용 예시
int main () {
...
St ( 구조체 변수 ) = {..};
...};
---- 보다시피 tyepdf로 선언하면 더 간략한 구조체 사용을 진행할 수 있다. 사용 예시에 대해서 알아보자
#include<stdio.h>
typedef struct a {
int num;
double total;
} St;
int main() {
St bb = { 2,100 };
struct a aa = {1,99.5 };
printf("num=%d total=%lf\n", aa.num, aa.total);
printf("num=%d total=%lf\n", bb.num, bb.total);
return 0;
} // 둘다 에러를 내보내지 않고 잘 출력된다
error C4996: 'scanf': This function or variable may be unsafe.
Consider using scanf_s instead. To disable deprecation, use
_CRT_SECURE_NO_WARNINGS. See online help for details.
에러발생 이유 : 시스템 안정성과 보안을 확보하기 위함
해결방법 : scanf_s 사용
struct a{
int num;
double total;
};
int main(){
struct a *pTest;
struct a p={1,100.99};
pTest=&p;
//p.num 과 *pTest.num의 출력값이 동일함
printf("num=%d total=%lf\n",(*pTest).num, (*pTest).total);
printf("num=%d total=%lf\n",pTest->num, pTest->.total);
// 둘 다 같은 값을 출력함. 즉, 포인터 변수를 통해 멤버 값 참조시 *대신 ->로 표현 가능
#include<stdio.h>
void test(struct a, struct a); // (1) 구조체 이름을 인자로 받거나
..
struct a t1,t2;
t1.num=1;
t2.num=2;
test( t1,t2 ); // (2) 구조체 변수로 함수를 호출하거나
..
void test( struct a aa, struct a bb){ // (3) 구조체 변수를 인자로 받거나
if(aa.num==bb.num) {
..
}