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 设备(。
由于您尝试修改被调用函数中的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
*/
}
相关文章:
- 如何正确编写指针函数声明?
- C++常规指针函数或模板
- 如何重新定义 C++ 指针函数?
- C++ 指向其他类函数的指针函数
- 指针到指针函数参数
- 将指向成员的指针函数传递到模板中
- C++ 在 none 常量指针函数中返回一个常量指针
- 如何使用指针函数编写/读取数组
- 是C 中的函数指针函数对象
- 如何从另一个类调用指向成员的指针函数
- 如何声明采用指向成员的指针函数的函数
- 如何构造一个以可变参数指针函数作为成员的类?
- c 通过值或指针函数语法
- 将typedef方法作为指针函数传递
- 从 Main 中的双指针函数打印出指针数组
- strcpy 对指针函数的引用
- 这是否仍然声明一种指针函数的别名?
- 将指向成员的指针函数与 std::shared_ptr 结合使用
- 'Incomplete type' 为标准::函数声明指向成员的指针函数模板参数时出错
- 从注入进程的 DLL 调用函数并更改指针函数的地址