从数组中查找最大数的代码

标签 c

<分区>

我编写了以下代码来从数字数组中找到最大数字。显然我的代码中有错误。这是一个段错误。请帮我鉴定一下。

#include <stdio.h>
void max(int n,int A[n]);

int main()
{
int n;
int A[n];
max(n,A[n]);
}

void max(int n,int A[n])
{
printf("Enter the number of elements you want in your array\n");
scanf("%d",&n);
int i;
printf("Enter the elements  in your array\n");
for(i=0;i<n;i++)
{
    scanf("%d",&A[i]);
}
int max=A[0];
for(i=1;i<n;i++)
{
    if(A[i]>max)
    {
        max=A[i];
    }
}
printf("%d",max);
}

最佳答案

int n;
int A[n];

您必须初始化 n 否则它包含垃圾值。现在,在这一点之后,您会遇到未定义的行为。

正确的代码应该是

#include <stdio.h>
#include <stdlib.h>
void printMax(int n,int A[]);

int main()
{
    size_t n;
    printf("Enter the number of elements you want in your array\n");
    if( scanf("%zu",&n) != 1){
        fprintf(stderr,"Error in input");
    }
    if( n <= 0){
        fprintf(stderr, "%s\n", "Error in input : Enter number >= 0 .");
    }
    int a[n];
    printf("Enter the elements  in your array\n");
    for(size_t i = 0; i < n; i++)
    {
        if( scanf("%d",&a[i]) != 1){
            fprintf(stderr,"%s\n","Error in input");
            exit(1);
        }
    }
    printMax(n,a);
    return 0;
}

void printMax(size_t n,int A[])
{
    int max=A[0];
    for(size_t i = 1; i < n; i++)
        if(A[i] > max)
            max = A[i];

    printf("%d",max);
}

关于从数组中查找最大数的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47699543/

相关文章:

c++ - 为什么 GCC 对 C++ <cmath> 比 C <math.h> 更有效地实现 isnan()?

c - 机器内存地址的内存地址? (C语言)

c - 为什么我不能像这样初始化数组?

c - 当程序通过 Makefile 在后台运行时,为什么 write() 调用不在终端上显示输出?

平均数的计算变得很高。我不明白为什么?

c - 用于 BOOL、LONG 和 WCHAR 等 Win32 typedef 的 Linux 头文件

c - 关于矩阵的动态分配

c - 将浮点指针设置为从头文件读取的字符数组

c - 简化 if 语句的算法

c - 4 位 4x20 LCD,采用 Atmega32