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

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

// 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
    */
}

现在:编译器警告我'variable "net" is used before its value is set'。确实如此,因为我没有足够的信息。它也会在运行时弹出,我只是忽略它。 我应该如何修改我的代码以使其更优雅? (顺便说一句,它必须是数组,而不是向量;然后我将它复制到 CUDA 设备)。

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

// 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,因此您需要传递 net by reference(因为您使用的是 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++ 代码。不要这样做。选择一个,并按预期使用其功能。