【问题标题】:Finding largest element in an array in C [duplicate]在C中查找数组中的最大元素[重复]
【发布时间】:2017-07-28 15:19:54
【问题描述】:

我的程序需要一个函数来查找数组的最大元素。然后它返回最大元素的位置。但是,在找到最大元素时,我只能使用指针算法。

#include <stdio.h>

int *largest(int *array, int size){
    int *p1 = array;
    int *count, max = *p1;
    for(*count = 0; count < p1 + size - 1; p1++){
        if (max < *p1){
            max = *p1;
            count++;
        }
    }
    return count;
}

int main(void){
    int *array, size = 10;

    printf("enter elements; ");
    for(int i = 0; i < size; i++){
        scanf("%d ", &array);
        array++;
    }

    printf("\nThe largest element in the array is in element %d", *largest(array, size));
}

但是,当我运行程序时,在输入元素的值后,它给了我:

segmentation fault (core dumped)

【问题讨论】:

  • 尝试为数组分配一些内存?然后将整数分配给每个数组位置?然后不要增加数组,因为它不再指向基数? (初学者
  • 您没有为数组分配内存。您需要添加行array = (int*)malloc(sizeof(int)*size);
  • 您在取消引用之前没有初始化count
  • 您还将整数读入int*,这不太可能结束。

标签: c arrays pointers segmentation-fault


【解决方案1】:

main函数中的错误:

您没有为数组分配内存。您需要添加行array = (int*) malloc(sizeof(int) * size);没有这条线你会得到segmentation fault

另一个错误是填充数组。数组已经是指针,因此您不必再次引用它。 现在你改变的是指针,而不是数组值

潜在的错误:在循环中填充数组时,会增加指针,因此会丢失有关数组开头的信息。您可以在循环执行array = array - size; 后再次获取它,但如果您提前中断循环,它将无法正常工作。最好使用临时指针。

函数最大的错误:

您创建了未分配的指针count,然后在for循环初始化中将值0写入未知地址。 原因segmentation fault

在 for 循环中,您尝试从地址 0 读取内存到地址 array + size - 2,但您想从数组的开头读取它到结尾从 arrayarray + size - 1 的数组。

返回count 没有意义,但总结起来,看例子。

指针只是内存地址的数字,因此当您不分配它或不分配现有指针时,它会随机指向内存并且操作系统不允许您访问该内存。您可能会从随机指针中读取一些内容,但是新编译器将初始值设置为 0。在 BSD 中,您可以从地址 0 读取,但 linux 会导致分段错误(我希望我没有切换它)。写入地址 0 会导致两个系统出现分段错误。

如果你得到有效的指针并且分配可能失败,你还应该检查函数,所以你也需要在分配后立即检查指针。总结一下:永远不要相信指针,总是检查它的有效性。

示例检查指针的有效性。

#include <stdio.h>

int *largest(int *array, int size){
    int *end = array + size; // address behind array
    int *max = *array; // address with largest value
    for(; array < end; ++array){ // you dont need initialization since the array points to beginning
        if (*max < *array){ // compare values, not address
            max = array; // save position of pointer with largest value
        }
    }
    return max; // return address with largest value
}

int main(void){
    int *array, size = 10;
    array = (int*)malloc(sizeof(int) * size); // allocate memory

    printf("enter elements; ");

    int *tmp = array; // temporary variable to not loose information about beginning of array
    for(int i = 0; i < size; i++){
        scanf("%d ", tmp); // reference is not needed since tmp is already pointer to value
        tmp++;
    }

    printf("\nThe largest element in the array is in element %d", *largest(array, size));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 2019-10-16
    相关资源
    最近更新 更多