排序错误输出+在Array中找到bigges

时间:2015-08-25 17:41:36

标签: c arrays

今天我创建了一个具有3个功能的程序:

sortArray(数组,长度);
removeDuplicateInArray(array,length);
max = findMax(数组,长度);

程序运行正常但是,如果我运行它多次,比方说三次,输出只有一个OK,其他两个是不同的,我认为在某种程度上与findMax函数中的数组长度有关,因为我删除重复项并且数组的大小不同。我不确定是否有问题。

该计划是这样的:

michi@michi-laptop:~$ ./program 
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -10 

,输出为:

9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 

Max = 9
michi@michi-laptop:~$ ./program 
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -10 

9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 

Max = 9
michi@michi-laptop:~$ ./program 
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -10 

9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 

Max = 2034093120
michi@michi-laptop:~$ ./program 
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -10 

9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 

Max = 912874208
michi@michi-laptop:~$ ./program 
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -10 

9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 

Max = 1269451840
michi@michi-laptop:~$ ./program 
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -10 

9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 

Max = 1946221408
michi@michi-laptop:~$ ./program 
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -10 

9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 

Max = 9
{
   "id": e872530a-27fc-4263-ad39-9a21568c31ef,
   "name": "dood",
   "friendId": "571746fc-686d-4170-a53e-7b7daca62fa0",
   "motherId": "99b65849-1f1c-4881-a1d0-c5ae432e83a2"
}

输出应为9,但输出并不总是9

2 个答案:

答案 0 :(得分:7)

removeDuplicateInArray函数会更改数组的长度,但在您的情况下,调用函数main并不知道新的长度。

您可以从函数返回新长度:

int removeDuplicateInArray(int *array, int length)
{
    // code as above

    return length;
}

并将其称为:

length = removeDuplicateInArray(array, length);

或者您可以将长度作为指针传递,这将反映出这些:

void removeDuplicateInArray(int *array, int *plength) ...
{
    int length = *plength;

    // use and modify length as above

    *plength = length;
}

并将其称为:

removeDuplicateInArray(array, &length);

我更喜欢第二种变体,因为它不会让您意外忘记返回值。

您看到的垃圾值会从数组范围之外移入,因为您循环到k < length并访问索引k + 1处的元素,该元素可能是{{1} },这是数组之外的一个元素。

答案 1 :(得分:3)

removeDuplicateInArray中通过指针传递length,以便稍后在主void removeDuplicateInArray(int *array, int *length)中使用正确的值。

相关问题