C++如何将未初始化的指针传递给函数

C++ how to pass an uninitialized pointer to a function

本文关键字:指针 函数 初始化 C++      更新时间:2023-10-16
// I need to download data from the (json-format) file net_f:
std::ifstream net_f("filename", std::ios::in | std::ios::binary);
// to a square int array *net of size n:
int n;
int * net;
load_net(net_f, &n, net);
// The size is initially unknown, so I want to do it in the procedure:
void load_net(std::ifstream& f, int *n, int *net)
{
    int size; // # of rows (or columns, it's square) in the array
    int net_size; // the array size in bytes
    /*
        some code here to process data from file
    */
    // Returning values:
    *n = size;
    // Only now I am able to allocate memory:
    *net = (int *)malloc(net_size);
    /*
        and do more code to set values
    */
}

现在:编译器警告我"变量"net"在设置其值之前被使用"。确实如此,因为我没有足够的信息。它也会在运行时弹出,我只是忽略它。我应该如何修改我的代码以使其更优雅?(顺便说一句,它必须是一个数组,而不是一个向量;我正在将其复制到 CUDA 设备(。

由于您尝试修改被调用函数中的net,因此您需要通过引用传递net(因为您使用的是C++(。此外,这也是n的首选:

void load_net(std::ifstream& f, int &n, int *&net)
{
    // ...
    /* Set output args */
    n = size;
    net = (int*)malloc(net_size);
}

C 方法是传递双指针(而不是投射 malloc 的结果!

void load_net(FILE* f, int *n, int **net)
{
    // ...
    /* Set output args */
    *n = size;
    *net = malloc(net_size);
}

您似乎正在编写 C 和 C++ 代码的混合。别这样。选择一个,并按预期使用其功能。

可以在函数参数中使用双指针,在函数中传递指针地址

// I need to download data from the (json-format) file net_f:
std::ifstream net_f("filename", std::ios::in | std::ios::binary);
// to a square int array *net of size n:
int n;
int *net;
load_net(net_f, &n, &net);
// The size is initially unknown, so I want to do it in the procedure:
void load_net(std::ifstream& f, int *n, int **net)
{
    int size; // # of rows (or columns, it's square) in the array
    int net_size; // the array size in bytes
    /*
        some code here to process data from file
    */
    // Returning values:
    *n = size;
    // Only now I am able to allocate memory:
    **net = (int *)malloc(net_size);
    /*
        and do more code to set values
    */
}