This is the first time I've ever had to use pointers to pointers aside from the all-so-known char **argv.
I have a couple of things I want to mention ahead of time. First of all, the intended functionality is to work with "arrays" of struct pointers. However in C, I cannot return an array of struct pointers so I am trying to return a pointer to heap memory which contains a bunch of struct pointers and work with that instead. Lastly, I'm a bit confused about the syntax of for example because this looks like an array of pointers, but I cannot actually create a function which returns an "array of pointers." However, as we know is the same as so is that actually an array of pointers or is argv a pointer to some heap memory of char pointers?
In any event, here's my code... I've done something wrong and I am thinking it's with my array of pointers stuff. The program should give us the number 6 when run but instead it gives us the number 0.
Code:
#include <stdio.h>
#include <stdlib.h>
int no_of_appearances(int *arr, size_t length, int integer);
int ip_compute_frequency(int arr[], int num, size_t length);
struct integer_profile *ip_create(int array[], int num, size_t length);
int ip_get_most_frequent_number(struct integer_profile **ip_table, size_t length);
struct integer_profile** create_ip_table(int arr[], size_t length);
struct integer_profile
{
int num;
int frequency;
};
int main(void)
{
int arr[] = {1,2,3,4,5,5,6,6,6,7};
struct integer_profile **ip_table = create_ip_table(arr, sizeof(arr));
int k = ip_get_most_frequent_number(ip_table, sizeof(arr));
printf("The most frequent number is %d\n", k);
return EXIT_SUCCESS;
}
//Creates and returns a new integer profile with frequency populated.
struct integer_profile *ip_create(int array[], int num, size_t length)
{
struct integer_profile *ip = malloc(sizeof(struct integer_profile));
ip->num = num;
ip->frequency = ip_compute_frequency(array, num, length);
return ip;
}
int ip_compute_frequency(int arr[], int num, size_t length)
{
size_t i;
int counter = 0;
for(i = 0; i < length; i++)
{
if(arr[i] == num) counter++;
}
return counter;
}
struct integer_profile **create_ip_table(int arr[], size_t length)
{
size_t i;
struct integer_profile **ip_table = malloc(sizeof(struct integer_profile*)*length);
for(i = 0; i < length; i++)
{
ip_table[i] = ip_create(arr, arr[i], length);
}
return ip_table;
}
int ip_get_most_frequent_number(struct integer_profile **ip_table, size_t length)
{
size_t i;
struct integer_profile *temp = ip_table[0];
for(i = 1; i < length; i++) // Start at 1 because ip_table[0] won't be greater than its own frequency
{
if(ip_table[i]->frequency > temp->frequency) temp = ip_table[i];
}
return temp->num;
}