所以我写了这个程序代表停车场作为一个位置,停车场的每个空间都是一点。我有一个checkSpace函数来检查空间是否被占用,由于某种原因,指向我的停车位集的指针发生了变化,或者在我将其传递给函数后数据发生了变化。为了测试它,我设置了停车场,我检查了一个空间,然后立即再次检查它,并且由于某种原因,返回值正在改变,当它不应该是。任何帮助将不胜感激!
struct carPark{
int spaces, levels;
unsigned char * park;
};
struct carPark * emptyCarPark(int levels, int spaces){
int chars = (spaces*levels)/8;
if((spaces*levels)%8 != 0){
chars++;
}
unsigned char park[chars];
for (int i = 0; i < chars; ++i){
park[i] = 0;
}
unsigned char * ptr = &park[0];
struct carPark * myPark = malloc(sizeof(struct carPark));
myPark->park = ptr;
myPark->spaces = spaces;
myPark->levels = levels;
return myPark;
}
int checkSpace(int level, int spaceNum, struct carPark * carpark){
int charPosition = ((level*carpark->spaces) + spaceNum)/8;
int bitPosition = ((level*carpark->spaces) + spaceNum)%8;
if(carpark->park[charPosition]&&(1<<bitPosition) != 0){
return 1;
}
return 0;
}
int main(int argc, char const *argv[]){
struct carPark * myPark = emptyCarPark(5,20);
printf("1st check: %d\n",checkSpace(1,1,myPark));
printf("Second check: %d\n",checkSpace(1,1,myPark));
return 0;
}
所以当我运行程序时,我得到了:
1st check: 0
Second check: 1
答案 0 :(得分:1)
查看下面的代码 - 在emptyCarPark()中,您将在堆栈上分配park数组,然后返回指向它的指针。一旦函数返回,就不再分配park数组,并且你有一个悬空指针 - 有关更多信息,请参阅:Cause of dangling pointers (Wikipedia)
unsigned char park[chars];
for (int i = 0; i < chars; ++i){
park[i] = 0;
}
// This is the pointer to an object on the stack.
unsigned char * ptr = &park[0];
struct carPark * myPark = malloc(sizeof(struct carPark));
myPark->park = ptr;