How to structure a function with a file and malloc

If I have a function that works with a file and pointer, for example:

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? Thanks.

+3
source share
2 answers

If you want to return it through a value other than the return value itself, you can simply pass a double pointer and dereference it.

C is strictly passed by value (all these functions are a copy of the original, and changes to it will not be returned back to the caller), but you can emulate the transfer by reference with pointers. You will look 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 that:

int *myVet;
int result = funzione (&myVet);

, malloc - C, .

, int, . int, , . , int, , .


, , , - NULL. , . , NULL , ( , , - , ..),.

:

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;
}
+3

- , FILE * , .

- :

 struct funzione_result {
   int fclose_result;
   int *vet;
 }

. , .

+1

All Articles