0

I know that i have to define at the beginning of the function what type it is supposed to return, but i dont know how to do it with pointer.. i try to do it like this with int * but its not working

int *sorting(int Num_Gaag, FILE *f) {
  typedef struct {
    int x;
    int y;
    int size;
    float power;
  } gaag;
  gaag *arrgaags;
  int i = 0, j;
  int counter = 0;

  arrgaags = malloc(sizeof(gaag) * Num_Gaag);
  fseek(f, 67, SEEK_SET);
  for (i = 0; i < Num_Gaag; i++)
    fscanf_s(f, "(%d,%d)   \t%d\t%f\n", &arrgaags[i].x, &arrgaags[i].y,
             &arrgaags[i].size, &arrgaags[i].power);
  return *arrgaags;
}

thank you!

3
  • 1
    You want return a int * or a gaag * ? Your minimal reproducible example is very unclear. Commented Jun 14, 2017 at 23:28
  • 2
    It will be difficult to use a gaag* outside of the function if its definition is only visible inside the function, even if you could somehow return it. Commented Jun 14, 2017 at 23:29
  • 1
    You can't return arrgaags if the function returns an int or int *; arrgaags (that sounds like a cry for help!) is a pointer to a structure type that is not accessible outside this function. Commented Jun 14, 2017 at 23:29

1 Answer 1

2

You need to declare the structure outside the function, then you can return gaag*.

typedef struct {
    int x;
    int y;
    int size;
    float power;
} gaag;

gaag *sorting(int Num_Gaag, FILE *f) {
    gaag *arrgaags;
    int i = 0, j;
    int counter = 0;

    arrgaags = malloc(sizeof(gaag) * Num_Gaag);
    fseek(f, 67, SEEK_SET);
    for (i = 0; i < Num_Gaag; i++)
        fscanf_s(f, "(%d,%d)   \t%d\t%f\n", &arrgaags[i].x, &arrgaags[i].y,
                 &arrgaags[i].size, &arrgaags[i].power);
    return arrgaags;
}

Note that you don't use * when returning the pointer, since that would return just the structure that the pointer points to (the first element of the array).

Sign up to request clarification or add additional context in comments.

2 Comments

But you don't free(arrgaags) it creates a memory leak.
The caller has to free it when they're done using the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.