c - 用户输入的类型数组

标签 c arrays ncurses

我写的是:

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/

相关文章:

c++ - crt0 是否加载 msvcrt.dll?

javascript - 按 [未知整数] 组遍历数组

ios - swift : Process UIImage data for use in Firebase custom TFLite model

c - 编译器如何解释在 C 中对数组执行的 sizeof() 运算符,因为数组实际上是一个常量指针?

c++ - 如何使用 ncurses 库让 Player 与 Monster 交互?

python - 使用 Python curses 自定义 RGB 颜色

cblas_dgemm 段错误

c - 在 C 中对多维数组列进行排序

c - 指针和链表节点创建错误

c - gcc/usr/bin/ld : error: cannot find -lncurses