c - 检查两个整数数组是否具有相同的元素,而不管它们的顺序如何
问题描述
此代码将卡片的值存储在arr.value
. 然后我尝试检查 arr.value 中的元素是否与 array 具有相同的元素cmpvalues
。如果它的元素与数组中的元素不匹配,cmpvalues
它应该打印出“错误”并返回 0。但是,即使输入正确,它仍然会打印出错误。一切都编译得很好,我只是找不到错误。
#include <stdio.h>
#define MAXCOLR 14
#define MAXLINE 100
#define MAXCHR 1024
#define _GNU_SOURCE
typedef struct {
char color[MAXCOLR];
int value;
} colorval_t;
int cmpfunc (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
int main (int argc, char **argv) {
size_t n;
int cmpvalues [] = {
65,
2,
3,
4,
5,
6,
7,
8,
9,
10,
74,
81,
75,
65,
2,
3,
4,
5,
6,
7,
8,
9,
10,
74,
81,
75
};
size_t ndx = 0;
char buf[MAXCHR];
colorval_t arr[MAXLINE] = {{ .color = "" }};
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) {
perror ("file open failed");
return 1;
}
while (ndx < MAXLINE && fgets (buf, MAXCHR, fp)) {
char c;
if (sscanf (buf, "%13s %d", arr[ndx].color, &arr[ndx].value) == 2)
ndx++;
else if (sscanf (buf, "%13s %c", arr[ndx].color, &c) == 2) {
arr[ndx].value = c;
ndx++;
}
}
if (fp != stdin) fclose (fp);
for (size_t i = 0; i < ndx; i++)
printf ("arr[%2zu] : %s %d\n", i, arr[i].color, arr[i].value);
qsort(arr, 26, sizeof(arr[26]), cmpfunc);
for( n = 0 ; n < 26; n++ ) {
printf("%d ", arr[n].value);
}
return 0;
}
输入:
RED A
RED 2
RED 3
RED 4
RED 5
RED 6
RED 7
RED 8
RED 9
RED 10
RED J
RED Q
RED K
BLACK A
BLACK 2
BLACK 3
BLACK 4
BLACK 5
BLACK 6
BLACK 7
BLACK 8
BLACK 9
BLACK 10
BLACK J
BLACK Q
BLACK K
解决方案
正确缩进代码表明该函数什么都不做并且总是返回0
(除非t1size == 0
)。
int all_match( int table1, int table2 , size_t t1size, size_t t2size)
{
for(size_t t1index = 0; t1index < t1size; t1index++)
{
int match = 0;
for(size_t t2index = 0; t2index < t2size; t2index++)
{
match = match ;
if(match)
{
break; // never happens
}
}
if(!match){
printf("error");
return 0; // always happens
}
}
return 1;
}
请注意,参数table
和table2
被忽略。
推荐阅读
- javascript - Javascript:For循环中的动态变量
- r - 在 R 中创建时间序列
- hadoop - 带/不带 HDFS 的 Alluxio
- python - 无法从不同的计算机通过 sqlalchemy 连接到 postgresql
- java - 我得到白屏
- android - 以 String.format 样式插入文本
- laravel - Laravel Socket.io,Redis 事件正在广播但未在客户端显示
- java - Swagger Codegen Resteasy - 捕获反序列化错误
- python - tkinter 多次使用相同的小部件
- java - 计算开始日期和结束日期之间经过的天数、月数和年数