c++ - 将指针传递给主函数后,无法正确打印内容

标签 c++ pointers function-pointers

我正在练习使用指针创建对象和访问数据。我创建了一个名为 BigNum 的结构来表示具有多个数字的数字。当我尝试在 readDigits 函数中打印结构的内容时,它可以打印得很好。但是,将指针传递给main函数后,stuct的内容打印出来是随机数。为什么?如何解决?

struct BigNum{
    int numDigits;    //the number of digits
    int *digits;  //the content of the big num
};

int main(){
    BigNum *numPtr = readDigits();
    for (int i=0; i<(numPtr->numDigits);i++ ){
       std::cout << (numPtr->digits)[i] << std::endl;
    }

    return 0;
}

BigNum* readDigits(){
    std::string digits;
    std::cout << "Input a big number:" << std::endl;
    std::cin >> digits; 

    int result[digits.length()];
    toInt(digits,result);

    BigNum *numPtr = new BigNum();
    numPtr->numDigits = digits.length();
    numPtr->digits = result;

/*     When I try to print in here, it's totally okay!

    std::cout << "Here is the content:" << std::endl;
    for (int i=0; i<numPtr->numDigits;i++ ){
    std::cout << (numPtr->digits)[i] << std::endl;
    }
    */

    return numPtr;
}

void toInt(std::string& str, int result[]){
    for (int i=0;i<str.length() ;i++ ){
    result[str.length()-i-1] = (int)(str[i]-'0');
    }
}

最佳答案

BigNum* readDigits(){
    //....
    int result[digits.length()];
    //....
    numPtr->digits = result;


    return numPtr;
}

result 存储在堆栈中。所以如果你把它作为numPtr的一部分返回,那么你一退出函数它就失效了。您必须使用 new 分配它,而不是将它存储在堆栈上。

关于c++ - 将指针传递给主函数后,无法正确打印内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26567432/

相关文章:

C++ 死亡钻石

C++迭代器双循环

c - struct-C 中字符串的二维数组

c - 函数指针赋值

c++ - GetTokenInformation 在 Windows XP 64 位上的意外行为

C++ 如何防止我的团队开发人员错误地使用整数版本的 abs?

c - 从 C 中的函数返回整数数组

c++ - 使用指针 C++ 进行转换

c - 指向结构的空指针

C 中函数指针的复合谓词