繁体   English   中英

如何使用指针/数组在C中实现这些方法?

[英]How to use pointer/array to implement these methods in C?

#include <stdlib.h>
#include <stdio.h>

#include "histo.h"

int main(int args, char *argv[])
{
  int histo[256];

  if (args == 2)
  {
    init_histogram(histo);
    cons_histogram(argv[1], histo);
    display_histogram(histo);
  }
  else
    exit(1);

  return 0;
}

histo.h 
#define MAX_CHAR 255 // largest ASCII(Extended) value for characters

typedef unsigned char byte; // may be useful for casting(s)

void init_histogram(int histo[]); // set all elements of the histogram to zero
void cons_histogram(const char string[], int histo[]); // construct the histogram from string
void most_frequent(const int histo[], char* ret_val); // report a most occurring character
void display_histogram(const int histo[]); // display the histogram sparsely

我给了这个main.c和histo.h来实现头文件中那些方法之后的histo.c文件。 我对int array histo感到困惑。 display_histogram仅采用一个参数,并应打印此输出:

% ./main hgfjkddjkrui3
3 appeared 1 times
d appeared 2 times
f appeared 1 times
g appeared 1 times
h appeared 1 times
i appeared 1 times
j appeared 2 times
k appeared 2 times
r appeared 1 times
u appeared 1 times

d是最经常发生的事情,有人可以向我解释为了获得此输出应该将哪些值存储在histo []中吗?

大概hist[]是一个数组,其中每个元素都包含给定ASCII字符的频率,并由ASCII字符索引。 init_histogram将其设置为0,而display_histogram打印非零条目。

看起来那些函数计算字符串的直方图。

我认为histo[]数组需要存储每个字符的计数。 因为您已将MAX_CHAR定义为255 ,所以我认为histo[]数组是256个整数的数组。

//vertical HISTOGRAM


#include<stdio.h>
#include<stdlib.h>
int main()
{
int c,i,j,arr[10],height=0;
system("clear");

for(i=0 ; i<10 ; i++)
    arr[i]=0;

 while( ( c=getchar() ) != EOF)
  {
     if(c >= '0' || c <='9')
     ++arr[c-'0'];
     if( arr[c-'0'] > height )
      {
      height = arr[c-'0'];
      } 
  }
printf("\n");
for(j=height ; j>0 ; j--)     // row
 {
  printf("%2d|",j);
  for ( i=0 ; i<=9 ; i++)  // column

    {
    if( j == arr[i] )
     {
     printf(" *|");
     arr[i]--;
     }
     else
         printf("  |");
    }

    printf("\n");
}
  printf("  |");
 for ( i=0 ; i<=9 ; i++)
     printf(" %d|",i);
     printf("\n  ------------DIGITS-------------");
     printf("\n");
return(0);
} 

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM