본문 바로가기
프로그래머스코딩테스트연습풀이/C언어

[프로그래머스/C언어] 2차원으로 만들기

by 코코쵸마 2023. 8. 14.

문제

정수 배열 num_list와 정수 n이 매개변수로 주어집니다. num_list를 다음 설명과 같이 2차원 배열로 바꿔 return하도록 solution 함수를 완성해주세요.

num_list가 [1, 2, 3, 4, 5, 6, 7, 8] 로 길이가 8이고 n이 2이므로 num_list를 2 * 4 배열로 다음과 같이 변경합니다. 2차원으로 바꿀 때에는 num_list의 원소들을 앞에서부터 n개씩 나눠 2차원 배열로 변경합니다.

 

솔루션

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

// num_list_len은 배열 num_list의 길이입니다.
int** solution(int num_list[], size_t num_list_len, int n) {
    // return 값은 malloc 등 동적 할당을 사용해주세요. 할당 길이는 상황에 맞게 변경해주세요.
    int** answer = (int**)malloc(150 * sizeof(int*));
    for(int i = 0; i < num_list_len; i++)
        answer[i] = (int*)malloc(150 * sizeof(int));
    int m = 0;
    for(int i = 0; i < num_list_len/n; i++)
        for(int j = 0; j < n; j++){
            answer[i][j] = num_list[m++];
            }
    return answer;
}

https://school.programmers.co.kr/learn/courses/30/lessons/120842

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr