如何将指针传递给函数并在函数 C++ 中动态分配内存

人气:903 发布:2022-10-16 标签: c++ pointers pass-by-reference pass-by-value function-definition

问题描述

我正在尝试声明一个指针并将该指针传递给分配了内存的函数.这是一个最小的例子:

I'm trying to declare a pointer and pass that pointer to a function where memory is allocated. Here is a minimal example:

#include <string>
#include <iostream>

using namespace std;

void alloc_mem(int &size, double *x);

int main()
{

        double *X;
        int imax;

        alloc_mem(imax, X);

        cout << "imax = " << imax << endl;
        for (int i = 0; i < imax; i++) {
                cout << "X = " << X[i] << endl;
        }

        delete[]X;
        return 0;

}

void alloc_mem(int &size, double *x)
{

        size = 10;
        x = new double[size];
        for (int i = 0; i < size; i++) {
                x[i] = (double)i;
        }

}

这段代码可以编译,但是当我尝试打印 X 的值时出现分段错误.我知道我没有正确地将变量传递到函数中,但我不知道该怎么做.我相信我正在对 x 的副本进行操作.

This code compiles, but I get a segmentation fault when I try to print out the values of X. I know that I'm not passing the variable into the function correctly, but I'm not sure how to do it. I believe that I'm operating on a copy of x.

此外,编写此代码是为了重现我在更大的代码中遇到的问题.

Also, this code was written to reproduce an issue I'm having in a much larger code.

推荐答案

参数 double *x 是函数 alloc_mem 的局部变量.当函数结束执行时,变量将被销毁.main 中的原始变量 X 不知道对这个参数做了什么,因为它是按值传递的,它是函数中使用的它的副本.

Parameter double *xis a local variable of function alloc_mem. When the function will end its execution the variable will be destroyed. The original variable X in main knows nothing what was done with this parameter because it was passed by value that is a copy of it was used in the function.

要么通过指针传递指针,要么通过引用传递指针.例如

Either pass the pointer by pointer or by reference. For example

void alloc_mem(int &size, double **x);

void alloc_mem(int &size, double * &x);

void alloc_mem(int &size, double **x) 
{
   size = 10;

   *x = new double [size];

   for ( int i = 0; i < size; i++ ) ( *x )[i] = i;
}

void alloc_mem(int &size, double * &x) 
{
   size = 10;

   x = new double [size];

   for ( int i = 0; i < size; i++ ) x[i] = i;
}

对于我来说,我会用以下方式定义函数

As for me I would define the function the following way

double * alloc_mem( int &size ) 
{
   size = 10;

   x = new double [size];

   for ( int i = 0; i < size; i++ ) x[i] = i;

   return x;
}

如果在调用函数之前就知道大小,那么它可以写得更简单

if size is known before calling the function then it could be written even simpler

double * alloc_mem( int size ) 
{
   x = new double [size];

   for ( int i = 0; i < size; i++ ) x[i] = i;

   return x;
}

考虑那个循环

   for ( int i = 0; i < size; i++ ) x[i] = i;

可以代替标准算法std::iota 例如

can be substituted for standard algorithm std::iota For example

std::iota( x, x + size, 0.0 );

486