你好,我正在尝试在C语言中使用void *作为通用数据类型。我想要一个机制,可以用它存储任何东西并获取任何东西。我写了一些代码,但在最后一个测试案例中失败了。如果有人能够帮我看一下代码,或者有其他的想法,请告诉我。
我知道我要存储什么类型的数据,在那个时候我知道数据类型,但在检索时,我只知道起始地址和大小。
下面是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
static void store( void *destination, void *source, size_t size ) {
memcpy ( (char*)destination, source, size);
}
static void retrieve ( void *destination, void *source, size_t size) {
memcpy ( destination, (char*)source, size);
}
void *storage_char_ptr = (void*) malloc ( sizeof( char* ));
void *storage_int_ptr = (void*) malloc ( sizeof(int*));
void *storage_int = (void*) malloc ( sizeof( int));
int main() {
int int_in = 65;
void *int_out_ptr;
int *ptr = ( int*) malloc ( sizeof(int));
memcpy ( ptr, &int_in, sizeof(int));
store ( storage_int_ptr, &ptr, sizeof(int*));
retrieve ( &int_out_ptr, storage_int_ptr, sizeof(int*));
assert ( int_in == *(int*)int_out_ptr);
char *char_in = "HelloWorld!!";
void *char_out;
store ( storage_char_ptr, &char_in, sizeof(char*));
retrieve ( &char_out, storage_char_ptr, sizeof(char*));
assert ( strcmp ( char_in, (char*)char_out ) == 0 );
char_in = _strdup("HelloWorld!!");
store ( storage_char_ptr, &char_in, sizeof(char*));
retrieve ( &char_out, storage_char_ptr, sizeof(char*));
assert ( strcmp ( char_in, (char*)char_out ) == 0 );
/* This is where it is failing */
int_in = 55;
void* int_out;
store ( storage_int, &int_in, sizeof(int));
retrieve ( &int_out, storage_int, sizeof(int));
assert ( 55 == *(int*)int_out);
}