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
*/
}
现在:编译器警告我在设置其值之前使用了变量net"".确实如此,因为我没有足够的信息.它也在运行时弹出,我只是忽略它.我应该如何修改我的代码以使其更优雅?(顺便说一句,它必须是一个数组,而不是一个向量;然后我将它复制到一个 CUDA 设备).
Now: the compiler warns me that 'variable "net" is used before its value is set'. 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).
推荐答案
由于你试图修改被调用函数中的net
,你需要通过net
参考(自你正在使用 C++).此外,这对于 n
也是首选:
Since you're trying to modify net
in the called function, you need to pass net
by reference (since you're using C++). Also, this would be preferred for n
as well:
void load_net(std::ifstream& f, int &n, int *&net)
{
// ...
/* Set output args */
n = size;
net = (int*)malloc(net_size);
}
C 的方式是传递一个双指针(并且不是强制转换 malloc
的结果!):
The C way would be to pass a double pointer (and not cast the result of malloc
!):
void load_net(FILE* f, int *n, int **net)
{
// ...
/* Set output args */
*n = size;
*net = malloc(net_size);
}
您似乎在编写 C 和 C++ 代码的混合体.不要这样做.选择一个,并按预期使用其功能.
You seem to be writing a mix of C and C++ code. Don't do this. Pick one, and use its features as they're intended.
这篇关于C++如何将未初始化的指针传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!