如何使用while循环和表示数组大小的变量打印出数组?

问题描述 投票:1回答:2

我继续得到相同的数字166和74.我想得到74 166 250 273 441 545 659 710 808 879 924 931.我真的不知道在哪里可以找到这个bug。我知道主要功能是正确的,但我不知道在哪里可以找到给我166和74的bug。

#include <stdio.h>

// Swap the values pointed to by a and b.
void swap( int *a, int *b )
{
  int temp = *a;

  *a = *b;

  *b = temp;
}

// Return a pointer to the element of the given array with the smallest value.
int *findSmallest( int *list, int len )
{
  int *smallest = list;
  for ( int i = 1; i < len; i++ ) {

       if(*smallest > *(list + i)) {

       *smallest = *(list + i);

       }

  }

  return smallest;
}

// Print the contents of the given list.
void printList( int *list, int len )
{
  while ( len ) {

    len--;

    printf("%d ", *(list + --len));


  }

  printf( "\n" );
}

int main()
{
  // A list of random-ish values.
  int list[] = { 808, 250, 74, 659, 931, 273, 545, 879, 924, 710, 441, 166 };
  int len = sizeof( list ) / sizeof( list[ 0 ] );

  // For each index, find the smallest item from the remaining
  // (unsorted) portion of the list.
  for ( int i = 0; i < len; i++ ) {

    int *p = findSmallest( list + i, len - i );

    // Swap the smallest item into the first position in the unsorted part of the
    // list.
    swap( list + i, p );
  }

  printList( list, len );
}
}
c
2个回答
3
投票
len--;
printf("%d ", *(list + --len));

你两次递减len


...但主要问题是findSmallest中的这一行:

*smallest = *(list + i);

这里smallest指向列表中的元素,并且您将覆盖该元素。相反,你应该改变smallest本身,因此它指向另一个元素:

smallest = (list + i);

有了这两个修复,这是输出:

931 924 879 808 710 659 545 441 273 250 166 74

列表,正确排序并打印回来。


0
投票

这段代码:

int *findSmallest( int *list, int len )
{
    int *smallest = list;
    for ( int i = 1; i < len; i++ ) {

       if(*smallest > *(list + i)) {

           *smallest = *(list + i);

       }

    }

应该调用swap()所以位置列表[0]中的原始值没有重叠在语句中:*smallest = *(list + i);

© www.soinside.com 2019 - 2024. All rights reserved.