Hi everyone,
What I have is a main function that takes input characters from the command prompt during the main function call, and coverts it to an integer array a using atoi. (starting at the 2nd character - the 1st is reserved for another call that I plan to reference later, and the 0th is obviously the ./function). A function is then called to find the mode of an array (the range of values in the array is 1-30). Now, when I run the whole thing, I get a segmentation fault (core dumped) for even number of arguments... Let me know if you need more explanation - It's late and I've been staring at it for too long...
Code:
#include <stdio.h>
#include <stdlib.h>
int get_mode(int a[], int count);
////////////MAIN/////////////////
int main(int argc, char *argv[])
{
int i, a[argc-2];
//printf ("type: %s\n number of arguments = %i\n", argv[1], argc);
for (i=2; i<argc; i++){
a[i-2] = atoi(argv[i]);
}
for (i = 0; i<argc-2; i++){
printf(" a[%i] = %i\n", i, a[i]);
}
printf("Mode: %d\n", get_mode(a, argc-2));
return 0;
}
////////////MODE/////////////////
int get_mode(int a[], int count)
{
int freq[31];
int i;
int mode;
/////intializing frequency array///////
for(i=0; i<=30; i++){
freq[i] = 0;
}
///// counting frequencies of #'s//////////
for (i = 0; i <= count; i++) {
++freq[ a[i] ];
}
////to see the individual frequencies/////
// for (i = 1; i <= 30; i++) {
// printf(" frequency of %i = %i\n", i, freq[i]);
// }
///finding mode//////////////
mode = 0;
for (i = 1; i < 30; i++) {
if (freq[i] > mode) {
mode = i;
}
}
return mode;
}