我需要将变量参数传递给另一个函数。问题是,这个参数是一个函数,我不知道如何确定函数的类型。例如,我有一个函数:char(*(char(c(,如何通过va_arg读取它?
void process(const char* typ ...)
{
char c;
va_list ap;
va_start(ap, typ);
while (*typ != 0)
{
switch (*typ)
{
case'p':
//change(va_arg(ap, char*), va_arg(ap, char(*)char(c)));
case 'f':
//filterr(va_arg(ap, char*), va_arg(ap, bool(*)char));
case 's':
char* a = va_arg(ap, char*);
char* b = va_arg(ap, char*);
encrypt(a, b);
break;
}
}
}
char changeToUppear(char c) {
return (c >= 'a' and c <= 'z') ? c - 32 : c;
}
bool leaveLowercase(char c) {
return (c < 'a' or c>'z');
}
char(*(char(c(,如何通过va_arg读取?
就像其他类型一样,接受它。函数类型为char (*)(char)
。在纠正了代码中的许多拼写错误后,以下代码将编译:
#include <iso646.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdbool.h>
void change(char (*func)(char), char *pnt);
char filterr(bool (*func)(char), char *pnt);
void encrypt(char *, char*);
void process(const char* typ, ...) {
// ^ !!
char c;
va_list ap;
va_start(ap, typ);
while (*typ != 0) {
switch (*typ) {
case'p': {
char *pnt = va_arg(ap, char*);
char (*func)(char) = va_arg(ap, char (*)(char));
change(pnt, func);
}
break;
case 'f': {
char *pnt = va_arg(ap, char*);
bool (*func)(char) = va_arg(ap, bool (*)(char));
filterr(pnt, func);
}
break;
case 's': {
char* a = va_arg(ap, char*); // it's not possible to declare variable after case!
char* b = va_arg(ap, char*);
encrypt(a, b);
}
break;
}
}
va_end(ap); // remember about va_end!
}
char changeToUppear(char c) {
// prefer toupper from ctype.h
return (c >= 'a' and c <= 'z') ? c - 32 : c;
}
bool leaveLowercase(char c) {
// prefer islower() != 0 from ctype.h
return (c < 'a' or c>'z');
}
int main()
{
char s1[] = "Ala ma kota.";
char s2[] = "Kot ma Ale!";
char s3[] = "to jest bardzo tajny tekst";
process("pfs",s1,changeToUppear,s2,leaveLowercase,s3,"TAJNE");
}