以下是遗留代码。
void InitializeStruct(someStruct* str); //function declaration
现在使用如下:
someStruct* myStruct = NULL;
int counter = 0;
int count = GetCount(); //obtains some count
if(count != 0)
{
myStruct = (someStruct*) malloc(count * sizeof(someStruct));
}
for(int i = 0; i < 3; ++i)
{
if(some condition) //for some condition
{
InitializeStruct(&myStruct[counter]); //null dererferenced here
counter ++;
}
}
解决此问题的正确方法是什么?
事先不知道myStruct
的大小。我猜,它抱怨取消引用null的原因是因为,如果count = 0
。
答案 0 :(得分:1)
您需要为三个mystruct
的数组分配空间,如下所示:
mystruct *array = NULL;
...
array = new mystruct[3]; // Allocate memory for the array
for(int i = 0 ; i < 3 ; ++i)
{
InitializeStruct(&array[i]);
}
...
delete[] array; // When you are done with the array, free the memory