2013-07-15 96 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; 
} 
相關問題