简体   繁体   English

数组和指针作为参数和返回值

[英]Arrays and Pointers as arguments and return values

#include <iostream>
using namespace std;

int getDegree()
{
    int degree;
    cout << "Enter degree of polynomial" << endl;

    cin >> degree;

    return degree;
}

int* getPoly(int degree)
{
    cout << "Enter coefficients in order of power of x. e.g. for 2 + x + 3x^2, enter 2 then 1     then 3" << endl;

    int coeff [degree +1];
    for (int i = 0; i <= degree; i++)
    {
        cin >> coeff[i];
    }

    return coeff;
}

int* polyder(int p[], int degree)
{
    int dp[degree];

    for(int i = 0; i < degree; i++)
    {
        dp[i] = p[i+1] * (i+1);
    }

    return dp;
}

int main(int argc, const char * argv[])
{
    int degree = getDegree();
    int p = *getPoly(degree);
    int dp = *polyder(&p, degree);

    for(int i = 0; i < degree +1; i++)
        cout << "   " << p[i] << " x^" << i;
    cout << endl;

    for(int i = 0; i < degree +1; i++)
        cout << "   " << dp[i] << " x^" << i;
    cout << endl;

    return 0;
}

I am getting an error during the print statements. 在打印语句期间出现错误。 I am not worried about the math involved, just how to pass the arrays between functions/methods. 我并不担心所涉及的数学,只是担心如何在函数/方法之间传递数组。

Can anyone find why this is not working? 谁能找到为什么这行不通? I am new to C++, used to Java. 我是C ++的新手,曾经使用过Java。

Can anyone find why this is not working? 谁能找到为什么这行不通?

In C++ variables are destroyed when the scope in which they were declared ends. 在C ++中,变量在声明它们的作用域结束时被销毁。 You return an address of a variable that doesn't exist when the function ends: 返回函数结束时不存在的变量的地址:

int* getPoly(int degree)
{
    int coeff [degree +1];
    // ...
    return coeff;
}

If you wish the variable still exists after the function ends, you have to allocate it using new : 如果希望函数结束后变量仍然存在,则必须使用new进行分配:

int* getPoly(int degree)
{
    int *coeff = new int[degree +1];
    // ...
    return coeff;
}

And, at the end of your main function (or wherever you don't need the array anymore), call delete[] to deallocate the memory: 并且,在主函数的末尾(或在不再需要该数组的任何地方),调用delete[]来释放内存:

int *p = getPoly(degree);
delete[] p;

The Array name is essentially a pointer to the first element of the array (as you can see in the code above, I've declared p as a pointer to int ), so you pass them to other functions just by providing their name: Array名称本质上是指向数组第一个元素的指针(如您在上面的代码中看到的,我已将p声明为int的指针),因此您只需提供它们的名称即可将它们传递给其他函数:

int* polyder(int p[], int degree){/*do something here*/}
// <-- some other code
int *p = getPoly(degree);
int* returnedArray = polyder(p,degree);

First of all, the line 首先,线

int coeff [degree +1];

is not a valid C++ statement unless 'degree' is a constant, even through some compilers may allow it. 除非'degree'是常量,否则它不是有效的C ++语句,即使通过某些编译器也可能允许它。

Even if some compiler allowed it, the space for coeff is allocated from the stack and will be invalid after the function returns. 即使某些编译器允许, coeff的空间也是从堆栈中分配的,并且在函数返回后将无效。 Hence, the line 因此,线

return coeff;

returns an memory location that will be invalid at its usage. 返回在使用时将无效的内存位置。

In order to return valid memory function, replace the line 为了返回有效的内存功能,请替换行

int coeff [degree +1];

by 通过

int* coeff = new int[degree];

You don't need degree+1 items in the array. 您不需要数组中的degree+1项目。

Similar changes are needed in the function polyder . 函数polyder中需要类似的更改。

The thing to remember about arrays in C++ is that unlike Java, they are not objects (at least in the way they are in Java). 关于C ++中的arrays ,要记住的一点是,与Java不同,它们不是对象(至少以Java的方式)。 They're simply pointers to a block of allocated memory, and the [] operator simply automatically does the math to move the pointer to the correct location. 它们只是指向分配的内存块的指针,而[]运算符仅会自动进行数学运算以将指针移至正确的位置。

When passing arrays between functions, you're basically just passing a pointer. 在函数之间传递数组时,基本上就是在传递指针。 Unless you want to get into some highly complicated and likely too much for your use case code, you should always pass the size of the array along with it to ensure that your indexes always stay in bounds. 除非您想为用例代码添加一些非常复杂且可能太多的内容,否则应始终将数组的大小与它一起传递,以确保索引始终保持在边界内。

And as the other answer points out, you need to ensure that the life cycle of the array lasts as long as you need it to. 就像其他答案指出的那样,您需要确保数组的生命周期可以持续到您需要的时间。 Simply returning a pointer to an object doesn't keep it alive like returning a reference does in Java. 简单地返回指向对象的指针并不能像在Java中返回引用那样使对象保持活动状态。

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

相关问题 用三重指针将数组作为参数 - Taking arrays as arguments with triple pointers How to pass a 2D arrays of pointers to 3D arrays of pointers (function and class) and return 3d arrays of values in C++? - How to pass a 2D arrays of pointers to 3D arrays of pointers (function and class) and return 3d arrays of values in C++? 我可以使用lambda指针数组来保存具有不同类型的参数/返回值的函数吗? - Can I have an array of lambda pointers in order to hold functions with different types of arguments/return values? 在向/从函数返回值/参数和类请求的数据传输期间是否复制了指向内存的指针? - Are pointers to memory copied during data transfer to/from function return values/arguments and class requests? 具有模板参数和返回类型的函数指针 - Function pointers with template arguments and return type 如何从方法返回动态指针数组 - How to return a dynamic arrays of pointers from a method 使用带有函数的指针来“返回”多维数组 - Using pointers with functions to “return” multidimensional arrays 传递指针数组并返回这些指针指向的值数组 - Passing an array of pointers and return an array of values pointed by those pointers 数组和指针 - Arrays & Pointers 指针是数组吗? - Are pointers arrays?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM