这段代码究竟出了什么问题......?

时间:2014-07-12 01:36:47

标签: c pointers

我试图用这个找到数组中最大的值......我做错了什么?

/*finds the largest value in an array*/
#include <stdio.h>
void find_large(int (*ar), int size, int *ptr1);
int main(void) {
    int array[10] = {1, 33, 4, 85, 132, -9, 0, 12, 99, 133};
    int size = sizeof(array) / sizeof(*array);
    int largest = 0;
    int *ptr1 = &largest;
    find_large(array, size, &ptr1);
    printf("The largest element is %d.\n", largest);
}

void find_large(int (*ar), int size, int *ptr1) {
    int count, largest = (*ar)[0];
    for(count = 0; count < size; count++) {
        if(*ar[count] > largest) {
            largest = (*ar)[0];
        }
    }
}

4 个答案:

答案 0 :(得分:2)

您没有在函数ptr1中使用find_large,因此永远不会返回最大的元素。

另请注意,您需要说ptr1而不是&ptr1

答案 1 :(得分:1)

#include <stdio.h>

void find_large(int *ar, int size, int *ptr1);

int main(void) {
    int array[10] = {1, 33, 4, 85, 132, -9, 0, 12, 99, 133};
    int size = sizeof(array) / sizeof(*array);
    int largest = 0;
    //int *ptr1 = &largest;//Not required
    find_large(array, size, &largest);
    printf("The largest element is %d.\n", largest);
    return 0;
}

void find_large(int *ar, int size, int *ptr1) {
    int count, largest = ar[0];
    for(count = 1; count < size; count++) {
        if(ar[count] > largest) {
            largest = ar[count];
        }
    }
    *ptr1 = largest;
}

答案 2 :(得分:0)

尝试这个,如果你想把指针参数作为一个数组,指针参数作为指针我添加了返回值,删除你函数中最大的单词():)

/*finds the largest value in an array*/
#include <stdio.h>

int find_large(int *ar, int size, int *ptr1);

int main(void) {

    int array[10] = {1, 33, 4, 85, 132, -9, 0, 12, 99, 133};
    int size = sizeof(array) / sizeof(*array);
    int largest = 0;
    largest = find_large(array, size, &largest);
    printf("The largest element is %d.\n", largest);
}

int find_large(int *ar, int size, int *ptr1) {
    int count; *ptr1 = ar[0];
    for(count = 0; count < size; count++) {
        if(ar[count] > *ptr1) {
           *ptr1 = ar[count];
        }
    }
    return *ptr1;
}

答案 3 :(得分:0)

让我们在你的函数中完全使用指针,因为没有括号的数组是该数组的第一个元素的指针,现在看到你的函数所有指针:)

/*finds the largest value in an array*/
#include <stdio.h>

int find_large(int *ar, int size, int *ptr1);

int main(void) {

    int array[10] = {1, 33, 4, 85, 132, -9, 0, 12, 99, 133};
    int size = sizeof(array) / sizeof(*array);
    int largest = 0;
    largest = find_large(array, size, &largest);
    printf("The largest element is %d.\n", largest);
}

int find_large(int *ar, int size, int *ptr1) {
    int *p_array;
    int count; *ptr1 = *ar;
    for(count = 0; count < size; count++) {
        if(*ar> *ptr1) {
           *ptr1 = *ar;
        }
     *ar++;
    }
    return *ptr1;
}