구조체 내에 포함 된 배열에 문자열을 저장하려고하고 있지만 액세스하는 데 어려움을 겪고 있습니다. 구조체는 다음과 같습니다구조체 내에서 문자열에 대한 포인터 할당 및 액세스
typedef struct {
void **storage;
int numStorage;
} Box;
상자 같은 초기화 :
문자열을 설정하기 위해b->numStorage = 1000000; // Or set more intelligently
Box *b = malloc(sizeof(Box));
// Create an array of pointers
b->storage = calloc(b->numStorage,sizeof(void *));
, 나는이 기능을 사용 :
void SetString(Box *b, int offset, const char * key)
{
// This may seem redundant but is necessary
// I know I could do strcpy, but made the following alternate
// this isn't the issue
char * keyValue = malloc(strlen(key) + 1);
memcpy(keyValue, key, strlen(key) + 1);
// Assign keyValue to the offset pointer
b->storage[offset*sizeof(void *)] = &keyValue;
// Check if it works
char ** ptr = b->storage[offset*sizeof(void *)];
// It does
printf("Hashcode %d, data contained %s\n", offset, *ptr);
}
문제는 때를 속인다 동일한 오프셋을 사용하여 다시 검색해보십시오.
// Return pointer to string
void *GetString(const Box *b, int offset, const char *key)
char ** ptr = b->storage[offset*sizeof(void *)];
if (ptr != NULL) {
printf("Data should be %s\n", *ptr);
return *ptr;
} else {
return NULL;
}
반환 된 포인터는 횡설수설합니다. 무엇이 잘못 될 수 있습니까?
좋은 지적으로 numStorage 비트를 수정했습니다. – Rio