2014-10-16 75 views
-2

我想用数组中的键创建表。有没有一种简单的方法来做到这一点。使用特定值计算函数调用的次数

int array1[] = {1,5,3,8,9,11}; 
// table[1] 
// table[5] 
// table[3] 

int count(int a) 
{ 

    //a is one of the values in array. array1[] = {1,5,3,8,9,11}; 
    // for ex 3. 
    // I have to figure out how many times this function was called with what values 1/5/3/8/9/11 
    table[3]++; 
} 
+0

创建一个全局数组(即在你的函数count()之外),将它设置为零(int)。如果遇到array1中的值,则增加indice值。 – aghoribaba 2014-10-16 18:35:06

回答

0

一个简单的代码

#include<stdio.h> 
int n = 6; //number of elements in array1 
int array1[] = {1,3,5,8,9,11}; 
int *funCount;//Count of elements in array1 
int count(int a) 
{ 
    int i; 
    for(i = 0; i < n; i++) 
    if(a == array1[i]) 
     break; 
    funCount[i]++; 
} 

int main() 
{ 
    funCount = (int*)calloc(n, sizeof(int)); 
    int i; 
    count(1); 
    count(3); 
    count(5); 
    count(8); 
    count(9); 
    count(11); 
    for(i = 0; i < n; i++) 
    printf("%d ",funCount[i]); 
    return 0; 
} 

这种做法是好的,如果你array1将是小! 否则我会建议你使用哈希

+0

甚至不会编译。 'n'不是一个常量表达式。 – 2014-10-16 18:42:23

+0

显然它不会编译!你能指望什么?从我完成的代码?他可以通过扫描来设置'n'的值! – Nullpointer 2014-10-16 18:43:00

+0

我不期望完整的代码,因为我不是OP。但是,这不是C,至少不是有效的C,因为它是错误的,它根本没有帮助。虽然他可以用'scanf()'设置'n'的值,但这样做不会有任何好处 - 全局数组的长度不能变化。 – 2014-10-16 18:44:01