0

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 ))
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
tomhoq
  • 59
  • 1
  • 6
  • `Data* aux, d1, d2;` should be `Data *aux, *d1, *d2;` – Ian Abbott Apr 08 '22 at 17:10
  • 1
    `Data* aux, d1, d2;` is equivalent to `Data *aux, d1, d2;`, and that might make it much clearer that only `aux` is a pointer, not `d1` or `d2`. This is one reason why I personally tend to define or declare only one variable per statement, where such mistakes are harder to make. – Some programmer dude Apr 08 '22 at 17:10
  • This is a good [example of why](https://stackoverflow.com/a/3770938/2505965) `int *foo` is generally preferred over `int* foo` in C. – Oka Apr 08 '22 at 17:13
  • In C syntax terms, `Data` is the *type-specifier*, and `* aux, d1, d2` is a list of three *declarator*s. `d1` and `d2` are *direct-declarator*s. `* aux` is a *pointer* followed by a *direct-declarator*. They could be declared in a different order: `Data d1, d2, *aux;`. – Ian Abbott Apr 08 '22 at 17:23

2 Answers2

0

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;
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

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;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335