0

I'm trying to pass an array of struct to a function that works with it and modify its content. I've read many articles but I still cannot find what I need.

I need to pass this array of struct to a function and work with the values of this array, and the modifications need to be global modifications.

Here, I'm actually sorting the values of the areas of this structure; the program gives me this warning and crashes:

warning: passing argument 1 of 'insersort' from incompatible pointer type [-Wincompatible-pointer-types]|

struct rectangle{
    char name[MAXC];
    float x;
    float y;
    float area;
    float perimeter;
};

void insersort(struct rectangle *rect[],int k)
{
    int i,j;
    float x;
    for(i=1;i<k;i++)
    {
        x=rect[i]->area;
        j=i-1;
        while(j>=0 && x<rect[j]->area)
        {
            rect[j+1]->area=rect[j]->area;
            j--;
        }
        rect[j]->area=x;
    }
    return;
}
..... 

I call the function like so:

struct rectangle rect[MAX];
insersort(rect,k); 
2
  • 1
    Too much indirection. Define the first function argument either as struct rectangle rect[] or as struct rectangle *rect but not both. Your struct rectangle *rect[] is an array of pointers. Commented Oct 24, 2020 at 15:26
  • 1
    ^^^^^ e.g. in insersort, the parameter should be struct rectangle rect[] and all rect[n]-> should be changed to rect[n]. Commented Oct 24, 2020 at 15:40

1 Answer 1

1

You wrote

void insersort(struct rectangle *rect[],int k)

and the body of insertof is written as though you meant

void insersort(struct rectangle (*rect)[],int k)

that is, array of pointer to rect

but you probably meant to write it as

void insersort(struct rectangle rect[],int k)

and not use -> inside insertof

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

3 Comments

How is it possible to use for example rect[i].area inside the function, I mean i need to work with pointers since the struct is passed by reference, If I pass the struct as void insersort(struct rectangle rect[],int k) is it passed by reference ? since there is no '*' specified in the parameter of the function, isn't the function working on a copy of it ? tried many and many modifications to the program and none worked. Thanks.
@Big-D: Because an array is always passed by reference.
Thanks, now it works, I was sure to have to use '->' in function to work with an array struct but i was wrong.

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.