[英]C functions to scan and print any basic data type array
I want to make scan_array and print_array function that can scan and print any basic data type array from stdin to stdout. 我想要使scan_array和print_array函数可以扫描和打印从stdin到stdout的任何基本数据类型数组。
What I got so far: 我到目前为止所得到的:
#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 function works for all basic types, I checked that with normal for loop inside main. scan_array函数适用于所有基本类型,我在main内部使用正常的for循环进行了检查。
print_array function works for INTS but not for any of other basic data types. print_array函数适用于INTS,但不适用于任何其他基本数据类型。
First thought was to change print_array def so that it takes function pointer instead of const char* fmt like this 首先想到的是更改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);
}
}
And than make double_printer: 并且比起double_printer:
void double_printer(void *el)
{
printf("%lf ", * (double *) el);
}
And it works perfectly. 而且效果很好。
print_array(a, sizeof(double), n, &double_printer);
But is there any way to make print_array without function pointer? 但是有没有办法在没有函数指针的情况下制作print_array?
Actually, it has some bugs regards to int
. 实际上,它与
int
。
Try input 127 128 255
, it should return 127 -128 -1
. 尝试输入
127 128 255
,它应该返回127 -128 -1
。
The problem is char *element, *end;
问题是
char *element, *end;
, and then dereference with *element
, it only reads 8 bits, not whole 32 bits regards of double
. ,然后用
*element
取消引用,它只读取8位,而不读取double
整个32位。
For this very case, I think define a macro is a better option, or you need to provide the function pointer as qsort
in c does. 对于这种情况,我认为定义宏是一个更好的选择,或者您需要像c中的
qsort
一样提供函数指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.