i wrote a combination output code for an input array. i wrote an input_array
function for an new array. i wrote an input_decimal_number
function for an size_t
type single-number. i set N as the number of elements in a combination. And i pass compilation. Here is code followed:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
size_t input_decimal_number(void);
size_t input_array(int *array);
void combination(const int *array, int *combination_array,
size_t start, const size_t end, const size_t N, size_t i);
int main(void)
{
size_t N, LEN;
int *array;
array = (int *)malloc(sizeof(int));
LEN = input_array(array);
printf("enter N value(0 < N <= %zd):\n", LEN); /* N is number of elements in a combination */
while ((N = input_decimal_number()) > LEN)
printf("N > %zd, enter N again: ", LEN);
int combination_array[N];
puts("Here are all combinations for this integer array:");
combination(array, combination_array, 0, LEN - 1, N, 0);
return 0;
}
size_t input_decimal_number(void)
{ /* here is a common size_t type single-number input functions */
size_t decimal_number;
_Bool input_check;
while ((input_check = fscanf(stdin, "%zd", &decimal_number)) != 1)
if (input_check != 1)
{
scanf("%*s");
fprintf(stdout, "invalid input, enter this number again: ");
}
return decimal_number;
}
size_t input_array(int *array)
{ /* this is input array functions */
size_t LEN = 0;
char buf[BUFSIZ];
void *alloc_check;
fprintf(stdout, "Enter decimal integer arrays(use spaces key to separate every number):\n");
while (fscanf(stdin, "%d", &array[LEN]) == 1)
{
alloc_check = realloc(array, (LEN + 1) * sizeof(int));
if (alloc_check == NULL)
;
else
array = (int *)alloc_check;
/* dynamically allocate memory for array */
LEN++;
if (getchar() == '\n')
break;
}
if (LEN == 0)
{
printf("no number entered correctly.\n");
exit(EXIT_FAILURE);
} /*if no input, exit the whole program */
setbuf(stdin, NULL);
setvbuf(stdin, buf, _IOLBF, BUFSIZ);
/* skip rest of input content */
return LEN;
}
void combination(const int *array, int *combination_array,
size_t start, const size_t end, const size_t N, size_t i)
{
/* this functions could find all combination of N elements in an array*/
if (i == N)
{
for (int k = 0; k < N; k++)
printf("%d ", combination_array[k]);
putchar('\n');
return;
}
for (start; start <= end && end - start + 1 >= N - i; start++)
/* "end-start+1 >= N-i" makes sure that including i at N will make a combination with remaining elements at remaining positions */
{
combination_array[i] = array[start];
combination(array, combination_array, start + 1, end, N, i + 1);
}
}
when i input such like 1 2 3 4 5 6
, and input N again it turned to be ok! But if i input 1 2 3 4 5 6 7
, it turned to be realloc(): invalid next size Aborted (core dumped)
, why?