2013-07-15 99 views
9

是否有可能存储在一个变量C数据类型?是否可以将C数据类型存储在变量中?

事情是这样的:

void* type = (byte*); 

这里有一个场景,其中我写了一个测试案例,并尝试使用某些数据类型printf中使用打印出一个字节数组,这取决于给定参数:

void print_byteArray(const void* expected, size_t size, 
     bool asChars, bool asWCharT) { 
    int iterations; 
    char* format; 
    if (asChars) { 
     iterations = (size/(sizeof (char))); 
     format = "%c"; 
    } else if (asWCharT) { 
     iterations = (size/(sizeof (wchar_t))); 
     format = "%lc"; 
    } else { 
     iterations = (size/(sizeof (byte))); 
     format = "%x"; 
    } 
    int i; 
    for (i = 0; i < iterations; i++) { 
     if (asChars) { 
      printf(format, ((char*) expected)[i]); 
     } else if (asWCharT) { 
      printf(format, ((wchar_t*) expected)[i]); 
     } else { 
      printf(format, ((byte*) expected)[i]); 
     } 
    } 
    fflush(stdout); 
} 

这看起来像效率低下的代码。我想像它是一个能规模下的for循环体,一条线路:

printf(format, ((type) expected)[i]); 

回答

12

没有,有没有这样的类型,它可以存储类型的标准C.

GCC提供typeof扩展可能有用。使用该关键字的语法类似于sizeof,但其结构在语义像typedef定义的类型名称。有关详细信息,请参见here

使用typeof的一些例子:

y声明有什么X点的类型。

typeof (*x) y; 

这将y声明为这样的值的数组。

typeof (*x) y[4]; 

将y声明为指针数组以字符:

typeof (typeof (char *)[4]) y; 

它等同于下面的传统C声明:

char *y[4]; 

要使用看到声明的含义typeof运算,以及为什么它可能是写一个有用的方法,用以下宏改写它:

#define pointer(T) typeof(T *) 
#define array(T, N) typeof(T [N]) 

现在声明可以被改写这样:

array (pointer (char), 4) y; 

因此,array (pointer (char), 4)是4个指针阵列烧焦的类型。

0

C是静态类型语言,所以你就必须建立自己的运行时类型系统。但是,如果只想打印任意数据的值,则可以使用printf%s并使用临时字符串缓冲区。这将在某些情况下,你要打印的数据是有界的工作:

#include <stdlib.h> /* EXIT_ */ 
#include <stdio.h> /* *printf */ 

#define PRINT_BUFFERS (4) 

struct Foo { 
    int key; 
    char value[32]; 
}; 

/** Assumes {key} is {[0, 99]} to comply with C90, otherwise use {snprintf}. */ 
static void Foo_to_string(const struct Foo *foo, char (*const a)[12]) { 
    sprintf(*a, "%d%.9s", foo->key, foo->value); 
} 
/** This is more convenient, but lacks generality. */ 
static const char *Foo_to_static(const struct Foo *foo) { 
    static char buffers[PRINT_BUFFERS][12]; 
    static unsigned n; 
    char *const a = buffers[n]; 
    sprintf(a, "%d%.9s", foo->key, foo->value); 
    n = (n + 1) % PRINT_BUFFERS; 
    return a; 
} 

int main(void) { 
    const struct Foo foo = { 42, "foo" }, bar = { 96, "bar" }, 
     baz = { 13, "baz_abcdefg" }; 
    /* This way is more general. */ 
    char a[12], b[12], c[12]; 
    Foo_to_string(&foo, &a); 
    Foo_to_string(&bar, &b); 
    Foo_to_string(&baz, &c); 
    printf ("Foo: %s; Bar: %s; Baz: %s.\n", a, b, c); 
    /* This way is convenient, but you have a max number of calls. */ 
    printf("Foo: %s; Bar: %s; Baz: %s.\n", Foo_to_static(&foo), 
     Foo_to_static(&bar), Foo_to_static(&baz)); 
    return EXIT_SUCCESS; 
} 
相关问题