:
#include <stdarg.h>
#include <stdlib.h>
int * intMallocInit (int length, ...) {
va_list args;
va_start (args, length);
int * arr = malloc (sizeof(int) * length);
if (arr == NULL) return NULL;
for (int i = 0; i < length; i++) {
arr[i] = va_arg(args, int);
}
va_end(args)
return arr;
}
:
int len = 3;
int * myArray = intMallocInit (len, 4, 5, 2);
if (myArray == NULL) return 0;
for (int i = 0; i < len; i++) {
printf("%d,", myArray [i]);
}
: 4,5,2,
. floatMallocInit() .., "int" "float"
void enum & , .
, , , .
#include <stdarg.h>
#include <stdlib.h>
enum {INT, FLOAT }
int getSize(int type) {
int typeSize = 0;
switch (type) {
case INT:
typeSize = sizeof (int);
break;
case FLOAT:
typeSize = sizeof (float);
break;
default:
return -1;
}
return typeSize;
}
void * mallocInit (int type, int length, ...) {
va_list args;
va_start (args, length);
int typeSize = getSize(type);
if (typeSize == -1) return NULL;
void * arr = malloc (typeSize * length);
if (arr == NULL) return NULL;
for (int i = 0; i < length; i++) {
switch(type) {
case INT:
arr[i] = va_args(args, int);
break;
}
}
va_end(args)
return arr;
}
float myArray = mallocInit (FLOAT, 3, 1, 5, 7);