Home > Net >  Invalid type argument of ->. Help me understanjd pointers?
Invalid type argument of ->. Help me understanjd pointers?

Time:04-09

So I am learning pointers and i think I mostly understand how they work but Im still learning how to use them correctly.

I wrote this code that receives a pointer to a list with pointers innit, each pointing to a struct called Data. I wanted to organize them by number, like say i have [29-10, 28-10, 3-1] the outcome would be [ 3-1; 2-10; 29-10 ]

#include <stdio.h>
#include <stdlib.h>
typedef struct
{
    int dia;
    int mes;
} Data;

void organiza(Data** l, int n)
{
    Data* aux, d1, d2;
    int j, i;
    for (i = 0;i<n-1;i   )
    {
        for (j= i   1;j<n;j  )
        {
            d1 = l[i];
            d2 = l[j];
            if (d1->mes > d2-> mes || (d1->mes == d2-> mes && d1->dia >= d2-> dia ))
            {
                aux == d1;
                d1 == d2;
                d2 == aux;
            }
        }
                
    }
}

While doing so I got a lot of errors which I dont understand why are happening:

error: incompatible types when assigning to type ‘Data’ {aka ‘struct ’} from type ‘Data *’ {aka ‘struct  *’}
d1 = l[i];
error: invalid type argument of ‘->’ (have ‘Data’ {aka ‘struct ’})
 if (d1->mes > d2-> mes || (d1->mes == d2-> mes && d1->dia >= d2-> dia ))

CodePudding user response:

In your case

Data* aux, d1, d2;

means, aux is a pointer, d1 and d2 are not. You need to write

Data *aux, *d1, *d2;

CodePudding user response:

This declaration

Data* aux, d1, d2;

is equivalent to

Data (* aux ), d1, d2;

or as the same

Data* aux;
Data d1, d2;

That is the variables d1 and d2 have the type Data.

So for example in these statements

d1 = l[i];
d2 = l[j];

the left operands have the type Data but the right operands of the assignments have the type Data * because the variable l has the type Data ** due to its declaration

void organiza(Data** l, int n)
              ^^^^^^^^

If you want to declare the variables d1 and d2 as pointers then you need to write

Data *aux, *d1, *d2;
  • Related