我创建了2个结构,一个称为产品,一个称为订单。
[我想要的是对由订单组成的数组进行排序,而这些订单包括一个产品数组,并且我使用了气泡排序算法来做到这一点。
该程序运行良好,但问题是它发出了一些我似乎无法理解的奇怪警告。
结构:
产品:
/* Structures */
typedef struct product
{
int ident;
char desc[MAX_CHARS]; /* string that describes a product eg. "bread" */
int price; /* price of the product*/
int weight; /* weight of the product eg. 2kg */
int quant; /* quantity of the product in stock */
int state_prod;
}product;
顺序:
typedef struct order
{
int ident_o;
product set_prod[MAX_PRODS_OD]; /* Set of products */
int state;
}order;
气泡排序算法:
void swap(char * xp,char * yp)
{
char * temp = xp;
xp = yp;
yp = temp;
}
/* A function to implement bubble sort */
void bubbleSort(product arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
/* Last i elements are already in place */
for (j = 0; j < n-i-1; j++)
if (arr[j].desc > arr[j+1].desc)
swap(&arr[j].desc, &arr[j+1].desc);
}
我只能使用此命令“ gcc -g -Wall -Wextra -Werror -ansi -pedantic”进行编译。
警告:
In function ‘bubbleSort’:
error: passing argument 1 of ‘swap’ from incompatible pointer type [-Werror=incompatible-pointer-types]
swap(&arr[j].desc, &arr[j+1].desc);
^
note: expected ‘char *’ but argument is of type ‘char (*)[64]’
void swap(char * xp,char * yp)
^~~~
error: passing argument 2 of ‘swap’ from incompatible pointer type [-Werror=incompatible-pointer-types]
swap(&arr[j].desc, &arr[j+1].desc);
^
note: expected ‘char *’ but argument is of type ‘char (*)[64]’
void swap(char * xp,char * yp)
^~~~
此错误消息
error: passing argument 1 of ‘swap’ from incompatible pointer type [-Werror=incompatible-pointer-types]
swap(&arr[j].desc, &arr[j+1].desc);
您向函数传递了一个指向声明如下的数组的指针
char desc[MAX_CHARS];
例如,使用类型为char( * )[MAX_CHARS]
的表达式&arr [j] .desc。但是功能参数的类型为char *
。你必须写
swap( arr[j].desc, arr[j+1].desc);
但是函数交换本身是不正确的。它不交换数组的元素。
void swap(char * xp,char * yp)
{
char * temp = xp;
xp = yp;
yp = temp;
}
例如,您可以通过以下方式定义它
void swap(char * xp,char * yp)
{
char temp[MAX_CHARS];
strcpy( temp, xp );
strcpy( xp, yp );
strcpy( yp, temp );
}
并且在if语句中
if (arr[j].desc > arr[j+1].desc)
您必须像自己比较字符串一样
if ( strcmp( arr[j].desc, arr[j+1].desc ) > 0 )