Reputation: 1158
If a I have a function that works with a file and a pointer, like this:
int funzione (int *vet)
{
FILE *fin;
if ( !(fin = fopen(name, "r")) )
return 1;
/* read informations from file (like num) */
vet = (int *) malloc (num*sizeof(int));
/* ... */
return fclose(fin);
}
How can I return vet
?
Thank you.
Upvotes: 3
Views: 125
Reputation: 881123
If you want to return it via other than the return value itself, you can simply pass in a double pointer and dereference that.
C is strictly pass-by-value (everything given to a function is a copy of the original and changes to it won't be reflected back to the caller) but you can emulate pass-by-reference with pointers. You would be looking at something like:
int funzione (int **pVet)
{
FILE *fin;
if ( !(fin = fopen(name, "r")) )
return 1;
/* read informations from file (like num) */
*pVet = malloc (num * sizeof(int));
/* ... */
return fclose(fin);
}
and you would call it thus:
int *myVet;
int result = funzione (&myVet);
You'll notice I've also removed the cast on return from malloc
- it's a bad idea to do this in C since it can hide certain subtle errors.
You shouldn't make the mistake of thinking, because you're passing in an int
pointer, that it will reflect back. If it was the int
you wanted to change, that would be okay. But, since it's the int
pointer you want to change, you need a pointer to that.
However, keep in mind that a common method of returning an error where pointers are involved is simply to return NULL. Whether that's suitable in your case is something you have to decide. If possible, I would consider returning the pointer itself and using NULL as an indication that the data wasn't obtainable (couldn't open file, couldn't allocate memory, data was wrong somehow, couldn't close file and so on).
That would go something like:
int *funzione (void) {
FILE *fin = fopen(name, "r");
if (fin == NULL) return NULL;
/* read informations from file (like num) */
int *pVet = malloc (num * sizeof(int));
if (pVet == NULL) return NULL;
// Populate pVet as needed. Any error must free it before
// returning NULL, such as with:
if (fclose(fin) != 0) {
free (pVet);
return NULL;
}
return pVet;
}
Upvotes: 3
Reputation: 2765
One option is to define a struct that holds onto the FILE* and the integer array you want to return.
You could define something like:
struct funzione_result {
int fclose_result;
int *vet;
}
And then assign to each member in your function. You'll still need to remember to free the vet array.
Upvotes: 1