取消引用指向整数的指针会导致分段错误

时间:2017-05-17 04:17:47

标签: c++ pointers

#include <iostream>


void PassByValue(int num) {
    std::cout << "inside PassByValue function" << std::endl;
}

void PassByRef(int &num) {
    std::cout << "inside PassByRef function " << std::endl;
    std::cout << "value of num is: " << num << std::endl;
    num = 50;
    std::cout << "value of num is: "<< num << std::endl;
}

int main() {
    int num1;
    int* pNum;
    num1 = 3;
    *pNum = 5;
    std::cout << "pNum is: " << *pNum << std::endl;
    PassByValue(num1);  
    PassByRef(*pNum);
}

这是我的代码,这个控制台在主要功能中与延迟线一起导致了问题。我在这里有点困惑。我的作业有问题吗?请帮忙。谢谢。

1 个答案:

答案 0 :(得分:2)

*pNum = 5; - pNum未初始化!
你需要先pNum指向一些真正的记忆 例如:

pNum = new int();
*pNum = 5;
....
// Or:
int num2;
pNum = &num2;
*pNum = 5;
....