This is a part of the question of my assignment and i am facing problems on how to access the array in a function.
Write a function that finds the 2nd minimum value among the given data items of float type, and returns the 2nd minimum. You should use pointer syntaxes over the data items.
//
// main.c
// DynamicMemoryManagement
//
// Created by Ramanpreet Singh on 12-10-20.
// Copyright (c) 2012 Ramanpreet Singh. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
float* assignMemory(int count);
void readFloatArray(float *f, int count);
float secondSmallest(float *f, int count);
int main(int argc, const char * argv[])
{
int count;
printf("Enter count: ");
scanf("%d", &count);
float *f = assignMemory(count);
printf("\nMemory of F: %p", f);
readFloatArray(f, count);
int i;
printf("\nYour Entered array is: ");
for (i = 0; i < count; i++)
{
printf("\n%9.2f", f[i]);
}
float secondSmall = secondSmallest(f, count);
if (secondSmall != 0)
{
printf("\nSecond Smallest number in array: %f", secondSmall);
}
}
/*
*/
float* assignMemory(int count)
{
float *f = (float*)malloc(count * sizeof(float));
return f;
}
/*
*/
void readFloatArray(float *f, int count)
{
printf("\n\nEnter you float values: \n");
int i;
for (i = 0; i < count; i++)
{
scanf("%f", &f[i]);
}
}
/*
*/
float secondSmallest(float *f, int count)
{
float *smallest = (float*) -1;
float *secondSmall = (float*) -1;
int i;
if (count == 1)
{
printf("\nYou have only one item in your array,\n"
"therefore, you have no second smallest item.");
return 0;
}
if(f[1] > f[0])
{
*smallest = f[0]; //The if works fine, for two elements
*secondSmall = f[1];
}
else if(f[1] < f[0])
{
*smallest = f[1]; // I GET AN ERROR AT THIS LINE - Bad access
*secondSmall = f[0];
}
for (i = 2; i < count; i++)
{
if (f[i] < *smallest)
{
*secondSmall = *smallest;
*smallest = f[i];
}
else if(f[i] < *secondSmall)
{
*secondSmall = f[i];
}
}
return *secondSmall;
}
So i want to know whatam i doing wrong... Theres no error in the program. But when i run the program and when it reaches the secondSmallest() function and tries to access the array passed through it, The program thorws an error. Any help with this function would be really great, thanks in advance and the help would be appreciated.