반응형
구조체 연산

구조체끼리의 연산은 불가능하다

하지만 멤버변수끼리의 연산은 가능합니다.

그리고 구조체끼리 할당은 가능합니다!

typedef struct
{
    int x;
    int y;
} Point;

int main()
{
    Point point1 = {3, 4};
    Point point2 = {1, 2};
    
    point1 + point2;		// 컴파일 에러
    point1.x + point2.x		// 컴파일 성공
    
    point1 = point2;		// 컴파일 성공
}

 

 

 

구조체 전달, 반환

아래의 코드처럼 구조체는 함수에서 매개변수로 전달이 될 수도, 반환형이 될 수 도 있습니다.

typedef struct
{
    char name[20];
    int age;
} Person;

void ModifyPerson(Person* person)
{
    person->age = 29;
}

Person CreatePerson()
{
    Person person;
    strcpy(person.name, "Oh_gun");
    person.age = 19;
    return person;
}

int main()
{
    Person person1 = CreatePerson();
    
    ModifyPerson(&person1);
}

 

 

 

구조체 초기화 방법

아래의 코드처럼 초기화할 수 있다.

typedef struct
{
    int x;
    int y;
} Point;

typedef sturct
{    
    Point center;
    double radius;
} Circle;

int main()
{
    Point point1 = { 3, 5 };
    Circle circle1 = { point1, 3.5 };		// x : 3, y : 5, radius : 3.5
    Circle circle2 = { {1}, 4.5 };		// x : 1, y : 0, radius : 4.5
    Circle circle3 = { 4, 5, 5.5 }; 		// x : 4, y : 5, radius : 5.5
}

 

 

반응형

 

반응형

'C' 카테고리의 다른 글

파일 입출력  (0) 2023.05.23
공용체(Union)  (0) 2023.05.23
구조체 변수 전달과 반환  (0) 2023.05.23
구조체 typedef 선언  (1) 2023.05.23
구조체  (0) 2023.05.22

+ Recent posts