-2

I have two files: mainfile.c and kmeans.c. I want to return the addresses of the buffers that are allocated in kmeans.c back to mainfile.c. The following is the process:

kmeans.c

void kmeans(int *cluster_assign, int *cluster_size,){
    cluster_assign = malloc(1000 * sizeof(int));
    cluster_size = malloc(5 * sizeof(int));

    // Some operations on both buffers

    return cluster_assign, cluster_size     //  <<<< Here I want to return the address of both buffers to main
}

mainfile.c

int main(){

    int *cluster_size = NULL;
    int *cluster_assign = NULL;

    kmeans(cluster_centers, cluster_size);

    // Here, I don't know how to acquire the addresses that were allocated in kmeans(...)

    return 0;
}

As you can see, if I don't return the addresses from kmeans.c, I cannot proceed in mainfile.c. I tried many ways including arrays of pointers but it was wrong. Any help is apprciated.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Don
  • 393
  • 3
  • 12

2 Answers2

0

A statement like

   return cluster_assign, cluster_size;

is the same as

   return cluster_size;

as, here, the comma-operator is in effect. The LHS of comma operator will be evaluated and discarded, the RHS operand will be the actual in-effect return value.

Basically, you cannot have a return statement returning values of two variable with a single statement from a function.

  • You can however, always form a structure (struct variable) with the members as two elements and return that.

  • As an alternative, you can take a pointer to the variable you want to be modified inside the function, do the operation and happily return void (nothing, return ; or simply omit the return statement.)

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

You can do that using double pointers

void kmeans(int **cluster_assign, int **cluster_size,){
    *cluster_assign = malloc(1000 * sizeof(int));
    *cluster_size = malloc(5 * sizeof(int));

    // Some operations on both buffers
}


int main(){

    int *cluster_size = NULL;
    int *cluster_assign = NULL;

    kmeans(&cluster_centers, &cluster_size);

}
LPs
  • 16,045
  • 8
  • 30
  • 61