문자열 여러개 합쳐야 하는데 free처리가 너무 불편해서..

원하는 만큼 문자열을 합칠 수 있는 함수입니당

프로토타입

char *str_joins(char **strs, int n)

파라미터

리턴 값

입력 예

int main(void)
{
	char *test;
	char *comma;
	char **arg;

	test = "hi";
	comma = ",";
	arg = (char *[3]){      // [n] 안에 합칠 문자열 개수를 넣기. count 함수 등 활용가능
		test,
		comma,
		test
	};

	// 방법 1
	char *output = str_joins(arg, 3);

	printf("%s\\n", output); // 출력 확인

	return (0);
}

// 방법 2
/* 변수에 할당하지 않아도 사용가능하다. */

char *output = str_joins((char *[3]){"hello", " world" " !"}, 3);

printf("%s\\n", output);  // 출력 확인

출력 예

// 방법 1
hi,hi

// 방법 2
hello world !

코드

char* str_joins(char **strs, int n)
{
	char *temp;
	char *output;
	int idx;

	idx = 0;
	output = strdup(strs[idx]);
	while (output && ++idx < n)
	{
		temp = strdup(output);
		// strdup 실패시 null 리턴 추가해도됨
		free(output);
		output = strjoin(temp, strs[idx]);
		free(temp);
	}
	return (output);
}