我的部分作业是使用函数操作一个包含团队分数的二维数组。我在使用他们希望我打印对手从最低到最高排序的所有分数的功能时遇到了麻烦。这是我所拥有的。
#include <stdio.h>
void arrangeScores(int array[][50], int team){
int low = array[0][0], tempArray[2][50], i, j = 0, instance = 1, flag, done = 0;
while(done == 0){ //perform while list is being sorted
for(i = 1; i < 50; ++i){ //checks for low value skipping flag number
if(array[team][i] == -999)
continue;
else if(array[team][i] < low)
low = array[0][i];
else
++instance; //handles duplicates
}
while(instance != 0){ //loads temp array
tempArray[team][j] = low;
for(i = 0; i < 50; ++i){
if(array[team][i] == low){
tempArray[team + 1][j] = array[team + 1][i];
array[team][i] = -999;
}
}
++j;
--instance;
}
instance = 1;
flag = 0;
for(i = 0; i < 50; ++i){ //checks to see if list is all flags(empty)
if(array[team][i] == -999)
++flag;
else if(flag == 49)
done = 1;
}
for(i = 0; i < 50; ++i) //updates low to new number
if(array[team][i] != -999 && array[team][i] != low){
low = array[team][i];
break;
}
}
for(i = 0; i < 50; ++i){ //reinitalizes origional array from sorted numbers
array[team][i] = tempArray[team][i];
array[team + 1][i] = tempArray[team + 1][i];
}
}
int main(){
int array[2][50];
int j = 0;
for(int i = 50; i > 0; --i){
array[0][j] = i;
++j;
}
for(int i = 0; i < 50; ++i){
array[1][i] = i;
}
arrangeScores(array, 0);
for(int i = 0; i < 50; ++i)
printf("%d %d\n", array[0][i], array[1][i]);
return 0;
}
出于某种原因,第二行中的每个元素都是 50.
你还没有告诉我们
arrangeScores()
应该做什么,所以这限制了我们进行技术分析。该函数做的最后一件事是:
for(int i = 0; i < 50; ++i){ //reinitalizes origional array from sorted numbers
array[team][i] = tempArray[team][i];
array[team + 1][i] = tempArray[team + 1][i];
}
这意味着我们需要弄清楚为什么右手边
tempArray[team + 1][i] = 50
。让我们使用 gdb 观察点:
$ gcc -g3 1.c
$ gdb ./a.out
(gdb) b arrangeScores
(gdb) r
(gdb) wa tempARray[1][0] == 50
(gdb) c
Continuing.
Hardware watchpoint 2: tempArray[1][0] == 50
Old value = 0
New value = 1
arrangeScores (array=0x7fffffffdce0, team=0) at 1.c:16
16 for(int i = 0; i < 50; i++) {
所以值在
for
循环之前改变了:
while(instance){ //loads temp array
tempArray[team][j] = low;
for(int i = 0; i < 50; i++) {
if(array[team][i] == low){
tempArray[team + 1][j] = array[team + 1][i];
array[team][i] = -999;
}
}
j++;
instance--;
}
让我们仔细看看
tempArray[team][j] = low
:
(gdb) p team
$24 = 0
(gdb) p j
$25 = 50
啊...
tempArray[2][50]
所以你有一个逻辑错误,j
是越界的,具体来说:
(gdb) p &tempArray[0][50]
$27 = (int *) 0x7fffffffdbd8
(gdb) p &tempArray[1][0]
$28 = (int *) 0x7fffffffdbd8
原来我们也可以让编译器告诉我们:
$ gcc -g3 -fsanitize=undefined 1.c
$ ./a.out
1.c:15:19: runtime error: index 50 out of bounds for type 'int [50]'
1.c:15:23: runtime error: store to address 0x7ffc6739dfb0 with insufficient space for an object of type 'int'
0x7ffc6739dfb0: note: pointer points here
32 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 32 00 00 00 32 00 00 00 32 00 00 00 32 00 00 00