问题
// 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'. 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).
回答1:
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);
}
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);
}
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.
回答2:
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
*/
}
来源:https://stackoverflow.com/questions/28690526/c-how-to-pass-an-uninitialized-pointer-to-a-function