count计算使用特定值调用函数的次数

时间:2014-10-16 18:29:47

标签: c

我想创建一个包含数组键的表。有没有一种简单的方法可以做到。

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]++;
}

1 个答案:

答案 0 :(得分: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会变小,这种方法是可行的! 否则我会建议你使用散列