简体   繁体   English

调用函数C后指针发生变化

[英]Pointer is changing after function call, C

So I've written this program to represent a car park as a bitset, each space in the car park being one bit. 因此,我编写了此程序,以一个停车位来表示一个停车场,停车场中的每个空间都是一个位。 I have a checkSpace function to check if a space is occupied or not and for some reason the pointer to my car park bitset changes or the data changes after I pass it into the function. 我有一个checkSpace函数来检查是否已占用空间,并且由于某种原因,指向停车场位集的指针发生更改,或者在将其传递给函数后,数据发生了变化。 To test it I set up the car park, I checked a space, then checked it again immediately after and for some reason the return value is changing when it shouldn't be. 为了测试它,我设置了停车场,检查了一个空间,然后在由于某种原因返回值在不应该更改的情况下立即更改,然后再次对其进行了检查。 Any help would be appreciated! 任何帮助,将不胜感激!

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

So when I run the program I get: 因此,当我运行程序时,我得到:

    1st check: 0
    Second check: 1

Look at the code below - in emptyCarPark() you are allocating the park array on the stack, and then returning a pointer to it. 看下面的代码-在emptyCarPark()中,您正在堆栈上分配park数组,然后返回指向它的指针。 As soon as the function returns, the park array is no longer allocated and you have a dangling pointer - for more information, see: Cause of dangling pointers (Wikipedia) 函数返回后,就不再分配park数组,并且您有一个悬空指针-有关更多信息,请参见: 悬空指针的原因(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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM