본문 바로가기
알고리즘/코딩 테스트 문제

[프로그래머스] 잘라서 배열로 저장하기(C)

by 진진리 2023. 9. 21.
728x90
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

// 파라미터로 주어지는 문자열은 const로 주어집니다. 변경하려면 문자열을 복사해서 사용하세요.
char** solution(const char* my_str, int n) {
    // return 값은 malloc 등 동적 할당을 사용해주세요. 할당 길이는 상황에 맞게 변경해주세요.
    int len = strlen(my_str);
    char** answer = (char**)malloc(sizeof(char*)*(len/n));
    for(int i=0; i<len; i++){
        answer[i] = (char*)malloc(sizeof(char)*n);
    }

    for(int i=0, j=0; i<=len/n, j<len; i++, j+=n){
        if(len-j<n) {strncpy(answer[i],my_str+j,len-j); answer[i][len-j]= '\0';}
        else {strncpy(answer[i],my_str+j,n); answer[i][n] = '\0';}
    }
    
    return answer;
}

for문에서의 j<len 조건 추가 + 밑의 if문에서 answer[i][len-j]='\0'; 수정 후 통과