我写的是:
printw("\nNow, Which is the type of data to be saved?\n");
printw("\n1- Integer\n2- Short-integer\n3- Char\n4- Float\n");
printw("\nSelect the number of the option (1-4)\n");
do{
scanf("%d",&h);
switch(h){
case 1:
int matriz[rows][columns];
break;
case 2:
short int matriz[rows][columns];
break;
case 3:
char matriz[rows][columns];
break;
case 4:
float matriz[rows][columns];
break;
default:
printw("\nYou have to enter a number between 1 and 4 :)\n");
break;
}
}while(h > 4 || h < 1);
(之前我定义了 h、行、列,并且我正在使用 ncurses)
我想做一个用户想要的类型的数组。但我意识到这不是办法。
最佳答案
C中类型泛型编程的典型案例。可以做到,但有点麻烦:
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define ROWS 2
#define COLS 3
typedef enum
{
TYPE_INT,
TYPE_SHORT,
TYPE_CHAR,
TYPE_FLOAT
} type_t;
typedef struct generic_t generic_t; // forward declaration, incomplete type
// generic print function type
typedef void(*print_func_t ) (const generic_t* ptr, size_t row, size_t col);
typedef struct generic_t
{
type_t type; // corresponding to selected data type
print_func_t print_func;
void* matrix2D;
} generic_t;
// specific print function just for float
void print_float (const generic_t* ptr, size_t row, size_t col);
int main()
{
generic_t data;
// take user input etc, determine type selected
// lets assume they picked float
data.type = TYPE_FLOAT;
data.print_func = print_float;
data.matrix2D = malloc (ROWS*COLS*sizeof(float));
float some_data[2][3] = // some random data:
{
{1, 2, 3},
{4, 5, 6},
};
memcpy(data.matrix2D, some_data, ROWS*COLS*sizeof(float));
for(size_t r=0; r<ROWS; r++)
{
for(size_t c=0; c<COLS; c++)
{
data.print_func(&data, r, c);
}
printf("\n");
}
free(data.matrix2D);
}
void print_float (const generic_t* ptr, size_t row, size_t col)
{
float(*fmatrix)[COLS] = ptr->matrix2D; // cast to a pointer to a 2D float array
printf("%f ", fmatrix[row][col]); // treat data as 2D array of float
}
您可以根据您想要对数据执行的操作创建类似的函数,每种可能的类型都有一个函数。
关于c - 用户输入的类型数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30217163/