例如在这个for循环中
for (i=L; (*i)->svt != NULL; i=(*i)->svt)
变量i 声明为
list *i
类型为struct element **。另一方面,数据成员svt 的类型为struct element *。因此这个任务
i=(*i)->svt
包含不同类型的操作数,没有从struct element *类型到struct element **类型的隐式转换。
请注意,如果由于此表达式而为空列表调用该函数,则该函数可能会调用未定义的行为
(*i)->svt != NULL;
也是一个元素数组的声明
char etat[1];
意义不大。
并为这样的指针引入这样的别名
typedef struct element *list;
一般来说不是一个好主意。它只会让代码的读者感到困惑。
没有必要通过指向它的指针通过引用将指向头节点的指针传递给函数tri(实现选择排序),因为指针本身在函数内没有被更改。
该函数可以通过以下方式声明和定义,如下面的演示程序所示。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct avion
{
int capacite;
} avion;
typedef struct element list;
typedef struct element
{
avion A;
struct element *svt;
} element;
int push_front( list **head, int capacite )
{
element *new_element = malloc( sizeof( element ) );
int success = new_element != NULL;
if ( success )
{
new_element->A.capacite = capacite;
new_element->svt = *head;
*head = new_element;
}
return success;
}
void display( const list *head )
{
for ( ; head != NULL; head = head->svt )
{
printf( "%d -> ", head->A.capacite );
}
puts( "null" );
}
void tri( list *head )
{
for ( ; head != NULL; head = head->svt )
{
element *min = head;
for ( element *current = head->svt; current != NULL; current = current->svt )
{
if ( current->A.capacite < min->A.capacite )
{
min = current;
}
}
if ( min != head )
{
avion tmp = min->A;
min->A = head->A;
head->A = tmp;
}
}
}
int main(void)
{
enum { N = 10 };
list *head = NULL;
srand( ( unsigned int )time( NULL ) );
for ( int i = 0; i < N; i++ )
{
push_front( &head, rand() % N );
}
display( head );
tri( head );
display( head );
return 0;
}
程序输出可能如下所示。
7 -> 1 -> 2 -> 6 -> 0 -> 9 -> 0 -> 9 -> 6 -> 0 -> null
0 -> 0 -> 0 -> 1 -> 2 -> 6 -> 6 -> 7 -> 9 -> 9 -> null
如果使用名称 list 的别名定义,则该函数可以看起来如演示程序中所示。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct avion
{
int capacite;
} avion;
typedef struct element *list;
typedef struct element
{
avion A;
struct element *svt;
} element;
int push_front( list *head, int capacite )
{
element *new_element = malloc( sizeof( element ) );
int success = new_element != NULL;
if ( success )
{
new_element->A.capacite = capacite;
new_element->svt = *head;
*head = new_element;
}
return success;
}
void display( list head )
{
for ( ; head != NULL; head = head->svt )
{
printf( "%d -> ", head->A.capacite );
}
puts( "null" );
}
void tri( list head )
{
for ( ; head != NULL; head = head->svt )
{
element *min = head;
for ( element *current = head->svt; current != NULL; current = current->svt )
{
if ( current->A.capacite < min->A.capacite )
{
min = current;
}
}
if ( min != head )
{
avion tmp = min->A;
min->A = head->A;
head->A = tmp;
}
}
}
int main(void)
{
enum { N = 10 };
list head = NULL;
srand( ( unsigned int )time( NULL ) );
for ( int i = 0; i < N; i++ )
{
push_front( &head, rand() % N );
}
display( head );
tri( head );
display( head );
return 0;
}