반응형
함수에서의 구조체 변수 전달과 반환

아래의 코드 처럼 매개변수로 구조체 변수를 받을 수 있고,

반환 값으로 구조체 변수를 받을 수 있습니다.

void ShowPosition(Point pos)
{
    printf("[%d, %d] \n", pos.xPos, pos.yPos);
}

Point GetCurrentPosition(void)
{
    Point cen;
	scanf("%d %d", &cen.xPos, &cen.yPos);
    return cen;		// 구조체 변수 cen이 반환.
}

 

 

 

구조체 기반 Call-by-reference

C언어에서는 Call-by-reference는 없다.

하지만 기능은 비슷하기에 편의상 이 글에서는

Call-by-reference라 부르겠습니다.

typedef struct point
{
    int xPos;
    int yPos;
} Point;

void Swap(Point* ptr)
{
    prt -> xPos = (ptr -> xPos) * -1;
    ptr -> yPos = (ptr -> yPos) * -1;
}

int main(void)
{
    Point pos = {5, -5};
    Swap(&pos);		// xPos : -5 yPos : 5
    Swap(&pos);		// xPos : 5 yPos : -5
}

 

반응형

 

반응형

'C' 카테고리의 다른 글

공용체(Union)  (0) 2023.05.23
구조체 변수 연산, 초기화  (0) 2023.05.23
구조체 typedef 선언  (1) 2023.05.23
구조체  (0) 2023.05.22
문자열 관련 함수  (0) 2023.05.22

+ Recent posts