2011-04-24 2 views
0

구조체 내에 포함 된 배열에 문자열을 저장하려고하고 있지만 액세스하는 데 어려움을 겪고 있습니다. 구조체는 다음과 같습니다구조체 내에서 문자열에 대한 포인터 할당 및 액세스

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; 
    } 

반환 된 포인터는 횡설수설합니다. 무엇이 잘못 될 수 있습니까?

답변

2

배열에 액세스 할 때 실제 메모리 오프셋을 지정할 필요가 없습니다. 단순히 색인을 제공하면 올바른 요소를 얻을 수 있습니다.

그래서, 세 번째 코드 블록에서 :

b->storage[offset] = keyValue; 

그리고 당신의 네 번째 :

또한
char *ptr = b->storage[offset]; 
if (ptr != NULL) { 
    printf("Data should be %s\n", ptr); 
    return ptr; 
} else { 
return NULL; 
} 

, 두 번째 코드 블록에, b->numStorage 이미 설정되어있는?

+0

좋은 지적으로 numStorage 비트를 수정했습니다. – Rio

2
b->storage[offset*sizeof(void *)] = &keyValue; 

로컬 변수 keyValue의 주소를 배열에 저장합니다. 함수가 완료되면이 주소는 유효하지 않게됩니다. 당신이 원하는 것 같아요 :

b->storage[offset*sizeof(void *)] = keyValue; 

그런 다음 검색하는 동안 해당 변경하십시오.

b->storage[offset*sizeof(void *)] = &keyValue 

설정된 로컬 변수 스토리지 키 값의 주소를 가리 키도록 [*는를 sizeof (무효 *) 오프셋]

1

이 않는다? 즉 함수가 반환 된 후에 더 이상 유효하지 않습니다.