在我添加while循环之前,这段代码运行良好。它应该采用4个字母,然后仅输出正确字母和位置的数量,以及正确字母的数量。但是,当我添加while循环(现在在代码中进行注释)时,在编译时出现了分段错误。出现问题的那行似乎是第33行,但我不知道为什么只有在添加while循环时它才行不通。
8 #include "cs1010.h"
9
10 long set_identical(long identical[4], char input[4], char guess[4])
11 {
12 for (long i = 0; i < 4; i += 1){
13 if (input[i] == guess[i]){
14 identical[i] += 1;
15 }
16 }
17 return *identical;
18 }
19
20 long sum(long identical[4])
21 {
22 long sum = 0;
23 for (long i = 0; i < 4; i += 1){
24 sum += identical[i];
25 }
26 return sum;
27 }
28
29 char change_array(char x[], long swap[])
30 {
31 for (long i = 0; i < 4; i += 1){
32 if (swap[i] == 1){
33 x[i] = '0';
34 }
35 }
36 return *x;
37 }
38
39 long set_color(long color, char guess[], char input[],
40 long swap1[], long swap2[])
41 {
42 *input = change_array(input, swap1);
43 *guess = change_array(guess, swap2);
44 for(long i = 0; i < 4; i += 1){
45 for (long j = 0; j < 4; j += 1){
46 if (input[i] != '0' && input[i] == guess[j]){
47 color += 1;
48 swap1[i] = 1;
49 swap2[j] = 1;
50 *input = change_array(input, swap1);
51 *guess = change_array(guess, swap2);
52 }
53 }
54 }
55 return color;
56 }
57
58 int main()
59 {
60 char* input = cs1010_read_word();
61 long position = 0;
62
63
64 //while(position != 4){
65 char* guess = cs1010_read_word();
66 long color = 0;
67 long identical[4] = {0};
68 long identical2[4] = {0};
69 *identical = set_identical(identical, input, guess);
70 position = sum(identical)
71 for (long i = 0; i < 4; i += 1){
72 identical2[i] = identical[i];
73 }
74
75 color = set_color(color, guess, input, identical, identical2);
76
77 cs1010_print_long(position);
78 cs1010_print_string(" ");
79 cs1010_println_long(color);
80 //}
81 }