Can I return a double * function?

Can I do something like this? Will this work?

double *vec_subtraction (char *a, char *b, int n)
{   
    double *result;
    int i;

    for(i=0; i<n; i++)
        result[i] = a[i]-b[i];

    return result;
}

and then basically:

double *vec=vec_substraction(a, b, n);
for(i=1; i<n; i++)         
    printf("%d", vec[i]);

a and b are vectors with the same number of elements, n is the number of elements.

+5
source share
7 answers

Yes you can, but you need to allocate memory for resultsomewhere.

Basically, you can either allocate memory inside vec_subtractionor outside vec_subtraction, if you choose the outside, you can do it statically or dynamically.

If you are going to highlight inside:

double *vec_subtraction (char *a, char *b, int n) {
    double *result = malloc(sizeof(double)*n);
    int i;
    for(i=0; i<n; i++)
        result[i] = a[i]-b[i];

    return result;
}

and basically:

double *vec;
// ...
vec = vec_subtraction(a, b, n);
// ...
free(vec); 

Do not forget the freeresult of the call vec_subtractionafter a while.


, :

void vec_subtraction (char *a, char *b, int n, double *result) {
    int i;
    for(i=0; i<n; i++)
        result[i] = a[i]-b[i];
}

:

// choose one of:
// double *vec = malloc(sizeof(double)*n);
// double vec[10]; // where 10= n.
vec_subtraction(a, b, n, vec);

// if you used *vec = malloc... remember to call free(vec).
+11

. , .

double *vec_subtraction( ... ) {
     double *result = malloc(sizeof(double)*n);

     ...

     return result;
}

. , .

:

void vec_subtraction( ..., double *result ) {


         ...

}

:

 double result[n];
 vec_subtraction(..., result);
+3

, , , - .

+2

, , double * . , . :

double *vec_subtraction (char *a, char *b, int n) {
double result[n];
int i;

for(i=0; i<n; i++)
    result[i] = a[i]-b[i];

    return &result[0]; //error,the local array will be gone when the function returns.
}

:

double *vec_subtraction (char *a, char *b, int n) {
double *result = malloc(sizeof(double)*n);
int i;
if(result == NULL)
   return NULL;

for(i=0; i<n; i++)
    result[i] = a[i]-b[i];

    return result; //remember to free() the returned pointer when done.
}
+2

vec_subtraction * . , - , , .

result = malloc(sizeof(double) * n);

, , :

free(vec);

( , C-) , , , . vec_subtraction. :

vec_subtraction (char *a, char *b, int n, double *result)

:

double vec[n];
...
vec_subtraction (a, b, n, &result);

-c, , , .

!

+1

- , . , , .

, , . , .

a b char, , double. , , , . , printf "% d", ( "% f" ). undefined.

+1

, :

result = malloc(sizeof(*result) * n);

.

, , .

0
source

All Articles