I'm doing my homework but there is some bugs I cannot fix Could you please help me? The question is using Dynamic memory allocation in C Find the some location of smallest negative element
The Function amnn is the "thing" I cannot fix
Thank u so much
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int nhapmang (int *p,int n)
{
int i;
for (i=0;i<n;i++)
{
printf ("Nhap vao a[%d] = ",i);
scanf ("%d",&*(p+i));
}
}
int inmang (int *p,int n)
{
for (int i=0;i<n;i++)
printf (" %d",*(p+i));
}
int amnn(int *p, int n)
{
int tg,tg1;
for (int i=0;i<n;i++)
{
if (*(p+i)<0)
{
tg=*(p+i);
break;
}
}
for (int i=0;i<n;i++)
{
if (*(p+i)<0 && (tg>*(p+i)))
{
tg1=i;
}
}
printf ("\nvi tri so am nho nhat trong mang la: a[%d]",tg1);
}
int main()
{
int *p, n,a,amnn1;
printf ("nhap vao n: ");
scanf ("%d",&n);
p=(int*)malloc(n*sizeof(int));
nhapmang (p,n);
printf ("\nin ma tran:");
inmang(p,n);
amnn(p,n);
return 0;
}
Input: n=5, a[0]=-9, a[1]=5, a[2]=-2, a[3]=-99, a[4]=-99 The result is a[3], a[4]
Unfortunately, I didn't understand the logic of your
amnn.It appears to only handle the case where there is one minimum value, so it would not handle your sample input.
I had to completely refactor your code. It is annotated:
UPDATE:
Perhaps, the better question to ask is:
What happens if we do not reset
mincount = 0?With the following sequence we would still get the correct answer (but only by luck):
However, if we have a list where the absolute/true minimum comes after a local/false minimum, without the reset, this will fail:
It will record/remember
-6. When it sees-7, it will not remove-6from the list.Here is the code modified to test this assertion:
Here is the program output:
As above, it can help to write code that checks the results for validity.
To help debug programs, we can also add extra
printfstatements that can show intermediate values and progress. To keep the code small and easy to read, I prefer to use a macro:Then, when we want to see the debug output, we compile with
-DDEBUG. Otherwise, the program runs normally (at full speed).