안녕하세요, C에서 void *를 일반적인 데이터 형식으로 사용하려고합니다. 내가 원하는 것은 무엇이든 저장할 수 있고 무엇이든 사용할 수있는 메커니즘입니다. 나는 약간의 코드를 작성했지만, 마지막 경우에는 실패하고있다. 아무도 코드를 살펴볼 수 있습니까? 다른 생각이 있다면 알려주세요.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);
}
어떻게 실패합니까? – MByD