我正在实现一个简单的程序,用C查找数组中的最大和最小元素。但是在某些情况下,我得到了意想不到的输出。请检查this输出。请检查下面的代码。根据输入没有得到所需的输出
#include<stdio.h>
#include<stdlib.h>
int largest(int *input)
{
int i=0,large=0;
for(;i<input[i]!='\0';i++)
{
if(input[i]>large)
large=input[i];
}
return large;
}
int smallest(int *input)
{
int i=0,small;
small=input[i];
for(;i<input[i]!='\0';i++)
{
if(input[i]<small)
small=input[i];
}
return small;
}
void main()
{
int *input;
int size,i=0,large,small;
printf("Enter size of array:\n");
scanf("%d",&size);
printf("Enter Numbers:\n");
input=(int *)malloc(size * sizeof(int));
for(;i<size;i++)
{
scanf("%d",input+i);
}
large=largest(input);
printf("Largest element is:%d, ",large);
small=smallest(input);
printf("Smallest element is:%d\n",small);
}
当我将大小传递给函数时,程序工作正常。
int largest(int *input,int size)
{
int i=0,large=0;
for(;i<size;i++)
{
if(input[i]>large)
large=input[i];
}
return large;
}
output通过执行上述功能。
我不明白这里发生了什么。请帮我找到解决办法。
'我的'input = calloc(size +1,sizeof(int));') – BLUEPIXY
@BLUEPIXY是的,它通过使用calloc函数来完美工作。感谢您的帮助。但是我仍然不明白为什么它在使用malloc时不工作?你能解释一下吗? –
您正试图与'0'进行比较,但它并不存在于输入数据的任何地方。 – BLUEPIXY