简体   繁体   English

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

Now: the compiler warns me that 'variable "net" is used before its value is set'. 现在:编译器警告我“在设置其值之前使用变量“ net””。 Indeed, it is, since I don't have enough information. 实际上,是因为我没有足够的信息。 It also pops-up during the runtime, and I just ignore it. 它也会在运行时弹出,而我只是忽略它。 How should I rework my code to make it more elegant? 我应该如何修改代码以使其更优雅? (BTW it has to be an array, not a vector; I'm copying it then to a CUDA device). (顺便说一句,它必须是数组,而不是向量;我将其复制到CUDA设备)。

Since you're trying to modify net in the called function, you need to pass net by reference (since you're using C++). 由于您试图在调用的函数中修改net ,因此需要通过引用传递net (因为您使用的是C ++)。 Also, this would be preferred for n as well: 同样,这对于n也将是首选的:

void load_net(std::ifstream& f, int &n, int *&net)
{
    // ...

    /* Set output args */
    n = size;
    net = (int*)malloc(net_size);
}

The C way would be to pass a double pointer (and not cast the result of malloc !): C方法是传递双指针( 而不转换 malloc的结果!):

void load_net(FILE* f, int *n, int **net)
{
    // ...

    /* Set output args */
    *n = size;
    *net = malloc(net_size);
}

You seem to be writing a mix of C and C++ code. 您似乎正在混合使用C和C ++代码。 Don't do this. 不要这样 Pick one, and use its features as they're intended. 选择一个,并按预期使用其功能。

you can use double pointer in function argument and pass pointer address in 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
    */
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM