-4

Hello I have a problem with one function. The Declaration is:

int load_clusters(char *filename, struct cluster_t **arr)

And i dont know how to work with these 2 pointers before **arr. I expect that i call it like this:

struct cluster_t *clusters;
load_clusters("file.txt",&clusters);

But I'm not sure if it is correct or not.

In the function I need to alocate memory for it. I think it have to be like this.

 arr = (struct cluster_t**)malloc(count * sizeof(struct cluster_t*));
 arr[0...x] = (struct cluster_t*)malloc(sizeof(struct cluster_t));
 arr[0...x]->size += 1;
.
.
.

But after all this I need to call function to print clusters.

 void print_clusters(struct cluster_t *carr, int narr)
{
    printf("Clusters:\n");
    for (int i = 0; i < narr; i++)
    {
        printf("cluster %d: ", i);
        print_cluster(&carr[i]); AND THIS DOESN'T WORK AS I EXPECT
    }
}

Thank for all help ;-)

  • 1
    Usually, ** means that the function will allocate memory and wants to return a pointer to the allocated memory, so you need to pass a pointer to a pointer. – stark Nov 28 '16 at 15:50

1 Answers1

0

In the function load_clusters, arr is a local variable, so any changes made to it are not reflected in the caller.

What you have is the address of a pointer variable you want to assign to. So dereference it and allocate space for an array of struct cluster_t.

*arr = malloc(count * sizeof(struct cluster_t));

Also, don't cast the return value of malloc.

Community
  • 1
  • 1
dbush
  • 205,898
  • 23
  • 218
  • 273