개발 기록/C Language

[C언어] 구조체 복사 strcpy, memcpy 알아보기

우준성 2021. 6. 15. 14:39

C언어에서는 구조체란 개념을 사용하고,

한 구조체변수에서 다른 구조체변수로 구조체를 복사하려면 아래처럼 할 수 있다.

 

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>

typedef struct _p {
	char name[20];
	int x;
	int y;
}Point;

int main(void)
{
	Point p1, p2;

	strcpy(p1.name, "구조체 복사");
	p1.x = 10;
	p1.y = 20;

	// 아래 출력되도록 p2에 p1의 값을 복사해보자.

	strcpy(p2.name, p1.name);
	p2.x = p1.x;
	p2.y = p1.y;

	printf("%s\n", p2.name);
	printf("%d %d\n", p2.x, p2.y);

	return 0;
}

코드처럼 문자열은 strcpy로, 숫자형은 바로 대입하면 된다.

 

 

 

 

그런데, 우리에게는 더 좋은 함수가 있다.

바로 구조체 자체를 복붙하는 memcpy이다.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>

typedef struct _p {
	char name[20];
	int x;
	int y;
}Point;

int main(void)
{
	Point p1, p2;

	strcpy(p1.name, "구조체 복사");
	p1.x = 10;
	p1.y = 20;

	// 아래 출력되도록 p2에 p1의 값을 복사해보자.

	memcpy(&p2, &p1, sizeof(Point));

	printf("%s\n", p2.name);
	printf("%d %d\n", p2.x, p2.y);

	return 0;
}

memcpy는 위처럼

memcpy(복사할 구조체 주소, 원본 구조체 주소, 크기);

이렇게 하면 된다

 

 

 

하지만 훨씬 편한 방법이 있다.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>

typedef struct _p {
	char name[20];
	int x;
	int y;
}Point;

int main(void)
{
	Point p1, p2;

	strcpy(p1.name, "구조체 복사");
	p1.x = 10;
	p1.y = 20;

	// 아래 출력되도록 p2에 p1의 값을 복사해보자.

	p2 = p1;

	printf("%s\n", p2.name);
	printf("%d %d\n", p2.x, p2.y);

	return 0;
}

p2 = p1;

바로 대입하면 된다.

위의 여러 방법을 알아놓자.

반응형