2014-12-15 3 views
1

초보 프로그래머입니다. 내 직접 그래프 프로그램에서 액세스 위반 오류가 발생했습니다. 왜 누군가가 내게 이유를 말할 수 있는지 궁금합니다.C++의 액세스 위반

다음은 문제 코드입니다 (걱정하지 마세요.별로 없습니다). 이 코드는 제 주된 기능입니다. 방금 파일에서 정보를 읽은 다음 구문 분석하고 InitialInsert라는 함수를 사용하여 양동이에 삽입하려고합니다.

//Store parsed file values 
sourceCity = line[0]; 
destinationCity = line[1]; 
miles = stoi(line[2]); 
cost = stoi(line[3]); 

//Insert parsed values into Info bucket 
graph.InitialInsert(sourceCity, destinationCity, miles, cost, size++); //Size is initialized to 0 

이것은 초기 삽입 기능입니다.

//InitialInsert function 
void Graph::InitialInsert(string source, string destination, int distance, int price, int index) 
{ 
    InfoBuckets[index]->sourceCity = source; 
    InfoBuckets[index]->destinationCity = destination; 
    InfoBuckets[index]->miles = distance; 
    InfoBuckets[index]->cost = price; 
} 

이것은 내 헤더 파일에서 가져온 것입니다.

static int const ARRAY_SIZE = 1000; 
struct InitialInfo 
{ 
    string sourceCity; 
    string destinationCity; 
    int miles; 
    int cost; 
}; 
InitialInfo* InfoBuckets[ARRAY_SIZE]; 

내 InitialInsert 함수의 첫 번째 라인을 쳤을 때 나는 오류 "액세스 위반 읽기 위치 0xCCCCCCE4"를 얻고있다. 이것은 어리석은 문제 일지 모르지만 누구든지 나를 도울 수 있습니까?

+4

'InfoBuckets' 포인트에서 포인터를 사용하기 전에 어디서나 좋은 포인터를 만들지 않는다고 생각합니다. – juanchopanza

+0

'size'는 어디에서 초기화 되었습니까? 함수를 처음 호출 할 때 어떤 가치가 있어야합니까? – wolfPack88

+0

개별'InitialInfo' 객체를위한 공간을 할당하지 않은 것 같습니다. –

답변

1

InifitalInfo의 1000 포인터 ARRAY가 정의되었지만 InitialInfo [0]이 초기화되지 않았습니다.

이 시도 : 객체의

배열 포인터 @Roddy의 recomends으로

InitialInfo *InfoBuckets[ARRAY_SIZE]; 

... 

InfoBuckets[0] = new InitialInfo(); // You need create the object first before using 

... 

void Graph::InitialInsert(string source, string destination, int distance, int price, int index) 
{ 
    InfoBuckets[index]->sourceCity = source; 
    InfoBuckets[index]->destinationCity = destination; 
    InfoBuckets[index]->miles = distance; 
    InfoBuckets[index]->cost = price; 
} 

InitialInfo InfoBuckets[ARRAY_SIZE]; 

... 

void Graph::InitialInsert(string source, string destination, int distance, int price, int index) 
{ 
    InfoBuckets[index].sourceCity = source; 
    InfoBuckets[index].destinationCity = destination; 
    InfoBuckets[index].miles = distance; 
    InfoBuckets[index].cost = price; 
} 

또는

배열, 스마트 페이지를 사용해야합니다 새 운영자 대신 ointers. 이 link에서 읽을 수 있습니다.

+0

'InitialInsert' 메쏘드에서'InfoBuckets [index] = new InitialInfo();'를했다면 어떻게 될까? –

+0

포인터의 배열을 제거하면 +1 기회가 생깁니다. 그렇지 않으면 적어도 make는 똑똑한 포인터입니다 :-( – Roddy

+0

David Isla의 조언을 받아서 작동 시켰습니다. (나는 어리석은 문제라는 것을 알고 있었지만 나를 비웃는 것에 감사드립니다.) –