mercredi 28 octobre 2015

C++ pointers - visual studio throws exception

void setToNull(int *tempPtr)
{

    int val = 25;
    tempPtr = &val;
    std::cout << "hh" << std::endl;
    std::cout << *tempPtr << std::endl;
    delete tempPtr;
    tempPtr = nullptr;
}

int main()
{ 
    int five = 5;
    int *ptr = &five;
    std::cout << *ptr;
    setToNull(ptr);
    if (ptr)
        std::cout << *ptr;
    else
        std::cout << " ptr is null" << std::endl;
    delete ptr;
    ptr=nullptr;
    return 0;
}

when I run this program in visual studio, an exception is thrown and this is not running till end.Would anyone explain to me why this is happening please ? Also is this code correct ?

Aucun commentaire:

Enregistrer un commentaire