본문 바로가기

C/코딩 기초 트레이닝

마지막 두 원소

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
 
int* solution(int num_list[], size_t num_list_len) {
    int n = num_list_len;
    int* answer = (int*)malloc((n+1)*sizeof(int));
    int a = num_list[n-1];
    int b = num_list[n-2];
    for (int i=0;i<num_list_len;i++) {
        answer[i] = num_list[i];
    }
    if(a>b)
        answer[n]=a-b;
    else
        answer[n]=a*2;
    return answer;
}
cs

 

answer = num_list 으로 코드를 작성했을 때 테스트를 통과하지 못하였다.

그 이유는 answer 포인터는 동적으로 할당된 메모리를 가리키는데, answer = num_list 는 answer 포인터에 num_list 배열의 시작 주소를 할당하는 것이기 때문에 answer는 더이상 동적으로 할당된 메모리를 가리키지 않게 된다. 그러므로 for 문을 이용해 주소가 아닌 값을 복사해야한다.

'C > 코딩 기초 트레이닝' 카테고리의 다른 글

이어 붙인 수  (0) 2024.02.05
코드 처리하기  (0) 2024.02.05
더 크게 합치기  (0) 2024.02.04
조건 문자열  (0) 2024.01.12
문자 리스트를 문자열로 변환하기  (0) 2024.01.12