【问题标题】:C functions to scan and print any basic data type array用于扫描和打印任何基本数据类型数组的 C 函数
【发布时间】:2016-12-13 09:33:47
【问题描述】:

我想做一个scan_array和print_array函数,可以扫描和打印从标准输入到标准输出的任何基本数据类型数组。

到目前为止我得到了什么:

#include<stdio.h>
void scan_array(void* base, size_t size_of_one, size_t n, const char* fmt)
{
    char *element, *end;
    end = (char *)base + size_of_one * n; 
    for (element = (char *)base; element < end; element += size_of_one) {
        scanf(fmt, element);
    }
}

void print_array(void* base, size_t size_of_one, size_t n, const char* fmt) 
{
    char *element, *end;
    end = (char *)base + size_of_one * n; 
    for (element = (char *)base; element < end; element += size_of_one) {
        printf(fmt, *element);
    }
}
int main()
{
    double a[3];
    size_t n = 3;
    scan_array(a, sizeof(double), n, "%lf");

    int i;
    for(i=0; i<n;i++) {
        printf("%lf ", a[i]);
    }

    putchar('\n');

    // prints zeros
    print_array(a, sizeof(double), n, "%lf ");
    return 0;
}

scan_array 函数适用于所有基本类型,我用 main 中的普通 for 循环检查了这一点。

print_array 函数适用于 INTS,但不适用于任何其他基本数据类型。

第一个想法是改变 print_array def 让它使用函数指针而不是像这样的 const char* fmt

void print_array(void* base, size_t size_of_one, size_t n, void (*data_printer)(void *el))
{
    char *element, *end;
    end = (char *)base + size_of_one * n; 
    for (element = (char*)base; element < end; element += size_of_one) {
        data_printer(element);
    }
}

比制作 double_printer:

void double_printer(void *el) 
{
    printf("%lf ", * (double *) el);
}

而且效果很好。

print_array(a, sizeof(double), n, &double_printer);

但是有没有什么方法可以让 print_array 没有函数指针呢?

【问题讨论】:

    标签: c arrays pointers


    【解决方案1】:

    实际上,它对int 有一些错误。

    尝试输入127 128 255,它应该返回127 -128 -1

    问题是char *element, *end;,然后用*element解引用,它只读取8位,而不是double的全部32位。

    对于这种情况,我认为定义一个宏是更好的选择,或者您需要像 c 中的qsort 那样提供函数指针。

    【讨论】:

      猜你喜欢
      • 2015-04-20
      • 1970-01-01
      • 2013-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多