简体   繁体   中英

Pointer to pointer of struct

I'm a bit confused about this subject. Let's say I have this struct:

typedef struct
{
    char a;
    int num;
} 
t_per;

and I want to sort a t_per* data by num . Then I would do something like:

void sort(t_per* data)
{
    int i = 0, j = 0;
    t_per aux;
    for(i = 0; data[i].num != 0; i++)
    {
        for(j = i + 1; data[j].num != 0; j++)
        {
            if(data[i].num > data[j].num)
            {
                aux = data[i];
                data[i] = data[j];
                data[j] = aux;
            }
        }
    }
}

But what if I have a t_per** data ? Would this be correct?

void sort(t_per** data)
{
    int i = 0, j = 0;
    t_per aux;
    for(i = 0; (*data[i]).num != 0; i++)
    {
        for(j = i + 1; (*data[j]).num != 0; j++)
        {
            if((*data[i]).num > (*data[j]).num)
            {
                aux = *data[i];
                *data[i] = *data[j];
                *data[j] = aux;
            }
        }
    }
}

Edited for legibility.

Explicitly writing data as an array of pointers may help. I am not sure of your purpose to use t_per** and generally it is adopted to reduce the cost of copying the t_per structures. This kind of sorting would manipulate on an array that stores pointers to the structures and it swaps the pointers in the array rather than t_per themselves. It should be just the same as void sort(T_PER[] data) in languages like java where objects are themselves pointers.

void sort(t_per* data[])
{
    int i = 0, j = 0;
    t_per* aux;
    for(i = 0; data[i]->num != 0; i++)
    {
        for(j = i + 1; data[j]->num != 0; j++)
        {
            if (data[i]->num > data[j]->num)
            {
                aux = data[i];
                data[i] = data[j];
                data[j] = aux;
            }
        }
    }
}

But if you decided to write or swap directly on t_per objects, your code would work. In any case, you should make sure that data is an array which stores t_per* .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM