C언어 배열 값 복사 - ceon-eo baeyeol gabs bogsa

이번 포스팅에서는 하나의 배열 요소를 다른 요소에게 복사하는 코드를 작성해보았습니다.

#include <stdio.h>
#define SIZE 10

void array_print(int a[], int size); // 배열 출력 함수
void array_copy(int a[], int b[], int size); // 배열 복사 함수

int main(void)
{
	int a[SIZE] = { 0, 1, 2, 3, 4, 5 };
	int b[SIZE] = { 0, };

	array_print(a, SIZE);
	array_copy(a, b, SIZE);
	array_print(b, SIZE);
	return 0;
}

void array_print(int a[], int size)
{
	int i;
	for (i = 0; i < SIZE; i++)
	{
		printf("%d ", a[i]);
	}
	printf("\n");
}

void array_copy(int a[], int b[], int size)
{
	int i, temp;

	for (i = 0; i < SIZE; i++)
	{
		temp = a[i];
		b[i] = temp;
		b[i] = a[i];
	}
	printf("\n");
}
C언어 배열 값 복사 - ceon-eo baeyeol gabs bogsa
▲ 위 코드 실행시 화면 출력값

그럼 오늘도 거운 딩!

값이 정확히 복사되고,
출력되었다.

두 함수 모두 1바이트 단위로 
값을 가져오는것은 똑같지만,

memcpy같은 경우에는
a = b; 처럼 직접 대입하고,

memmove같은 경우에는
a=temp;
a=b;
b=temp;
이런식으로 임시변수를 이용해 대입한다.

그렇기때문에 예전에 memcpy같은 경우 
memmove보다 빠르지만 자기 자신을 복사할때
값이 교환되지않아 모두 첫번째 값이 들어가는
오류가 있었다고 한다.
그래서 자기자신을 복사할때에는 memmove를 쓰고,
다른배열을 복사할때에는 memcpy를 썼다고한다.

그렇지만 최근 나오는 비쥬얼스튜디오에서는
그런 부분이 고쳐졌기 때문에 어떤 함수를 써도
오류가 나지않는다.

결국 두 함수는 이제 거의 같은함수인것같다.

1 개념[ | ]

배열 복사

2 memcpy() 함수 이용[ | ]

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

#define ARR_SIZE 6

void printArray(int *arr, int n) {
    int i;
    for (i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    const int src[ARR_SIZE] = {0, 1, 2, 3, 4, 5};
    int dst[ARR_SIZE];
    memcpy(dst, src, sizeof(src));
    printArray(dst, ARR_SIZE);
    return 0;
}

3 자작 함수 사용[ | ]

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

#define ARR_SIZE 6

void arrayCopy(int *dst, const int *src, int n) {
	int i;
	for (i = 0; i < n; i++) {
		dst[i] = src[i];
	}
}

void printArray(int *arr, int n) {
	int i;
	for (i = 0; i < n; i++) {
		printf("%d ", arr[i]);
	}
	printf("\n");
}

int main() {
	const int src[ARR_SIZE] = {0, 1, 2, 3, 4, 5};
	int dst[ARR_SIZE];
	arrayCopy(dst, src, ARR_SIZE);
	printArray(dst, ARR_SIZE);
	return 0;
}

4 같이 보기[ | ]

  • C언어 memcpy()