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

时间:2015-02-24 07:46:11

标签: c++ arrays pointers

// 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设备上。)

2 个答案:

答案 0 :(得分:3)

由于您尝试修改被调用函数中的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 ++代码的混合体。不要这样做。选择一个,并按照预期使用其功能。

答案 1 :(得分:0)

你可以在函数参数中使用双指针并在函数

中传递指针地址
// 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
    */
}