─ 狀況說明
下面程式碼一直出現「變數尚未初始化」的錯誤訊息
void main()
{
InspectionRegion *test;
test->regionHeight = 10;
test->startPointsOfEachRow = new hsPoint[10];
test->endPointsOfEachRow = new hsPoint[10];
for (int i = 0; i < 10; i++)
{
(test->startPointsOfEachRow + i)->X = i;
(test->startPointsOfEachRow + i)->Y = i + 10;
(test->endPointsOfEachRow + i)->X = i + 20;
(test->endPointsOfEachRow + i)->Y = i + 30;
}
}
─ 想法
我一開始以為是没把那塊記憶體歸零,後來才想起來,是我没有將結構指標指向該結構!
所謂的指標的型態,是代表這個指標指向什麼資料型態的變數,而我只是宣告了一個指向InspectionRegion這個結構的指標,並没指向任何InspectionRegion的結構,所以這時候要用new算子向記憶體要一個InspectionRegion的空間,並將指標指過去。
─ 程式碼
typedef struct
{
int X;
int Y;
}hsPoint;
typedef struct
{
int regionHeight;
hsPoint *startPointsOfEachRow;
hsPoint *endPointsOfEachRow;
}InspectionRegion;
void main()
{
InspectionRegion *test = new InspectionRegion;
test->regionHeight = 10;
test->startPointsOfEachRow = new hsPoint[10];
test->endPointsOfEachRow = new hsPoint[10];
for (int i = 0; i < 10; i++)
{
(test->startPointsOfEachRow + i)->X = i;
(test->startPointsOfEachRow + i)->Y = i + 10;
(test->endPointsOfEachRow + i)->X = i + 20;
(test->endPointsOfEachRow + i)->Y = i + 30;
}
}
這封郵件來自 Evernote。Evernote 是您專屬的工作空間,免費下載 Evernote |
沒有留言:
張貼留言