Okay, es gab ein paar Bugs. Ich habe zwei Versionen produziert. Eine mit den Käfern kommentiert und eine zweite mit Dingen aufgeräumt.
Hier ist die kommentierte Version [bitte die unentgeltlichen Stil Bereinigungs verzeihen]:
/* Finds the largest and smallest elements in an array */
#include <stdio.h>
#define N 10
void max_min(int a[], int n, int *max, int *min);
int
main(void)
{
int b[N],
i,
*big,
*small;
printf("Enter %d numbers: ", N);
for (i = 0; i < N; i++)
scanf("%d", &b[i]);
// BUG1: big/small have not been initialized to point to anything
max_min(b, N, big, small);
printf("Largest: %d\n", *big);
printf("Smallest: %d\n", *small);
return 0;
}
void
max_min(int a[], int n, int *max, int *min)
{
int *p;
// BUG2: because of BUG1 above, this will segfault
// BUG3: because p is never initialized, dereferencing it (via "*p") will
// segfault
*max = *min = *p = a[0];
// BUG4: this will run past the end of the "a" array because there is
// no guarantee of a matching sentinel value (i.e. EOF/-1)
// in fact, using a sentinel is wrong because the "a" array can have _any_
// value (i.e. there is _no_ sentinel value that can be used)
while (*p != EOF) {
// BUG5: when max or min gets set, we're changing what they point to
// but this will _not_ change caller's values
if (*p > *max)
max = p;
else if (*p < *min)
min = p;
p++;
}
}
Hier ist ein gereinigter und Arbeitsversion. Beachten Sie insbesondere die Änderung der big/small
in Haupt von int *
zu int
mit einer entsprechenden Änderung im Aufruf von max_min
:
/* Finds the largest and smallest elements in an array */
#include <stdio.h>
#define N 10
void max_min(int a[], int n, int *max, int *min);
int
main(void)
{
int b[N],
i,
big,
small;
printf("Enter %d numbers: ", N);
for (i = 0; i < N; i++)
scanf("%d", &b[i]);
max_min(b, N, &big, &small);
printf("Largest: %d\n", big);
printf("Smallest: %d\n", small);
return 0;
}
void
max_min(int a[], int n, int *max, int *min)
{
int *p;
int val;
p = &a[0];
*max = *min = *p;
for (int i = 0; i < n; ++i, ++p) {
val = *p;
if (val > *max)
*max = val;
else if (val < *min)
*min = val;
}
}
http://ideone.com/GbsQ3q – BLUEPIXY
1. Bitte geben Sie die Einbuchtung auszusortieren. 2, Use3 geschweifte Klammern - spart zukünftige Probleme –
Kennen Sie den Unterschied zwischen '* p = i;' und 'p = & i;'? – immibis