我正在Ubuntu中使用GCC创建一个小型ANSI C应用程序。我目前已经创建了两个C源文件和一个头文件(我的实验室教授要求我这样做。)
我的“主要”C档案:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "alphaStats.h"
int main(void) {
int ABStats[26] = { 0 };
int *pABStats = ABStats;
char *pAr = Ar;
GetFrequency(pAr, pABStats);
return EXIT_SUCCESS;
}
我的alphaStats.h头文件:
#include "alphaStats.c"
char Ar[] = {"All Gaul is divided into three parts, one of which the Belgae inhabit, the Aquitani another, those who in their own language are called Celts, in our Gauls, the third. All these differ from each other in language, customs and laws. The river Garonne separates the Gauls from the Aquitani; the Marne and the Seine separate them from the Belgae. Of all these, the Belgae are the bravest, because they are furthest from the civilization and refinement of [our] Province, and merchants least frequently resort to them, and import those things which tend to effeminate the mind; and they are the nearest to the Germans, who dwell beyond the Rhine , with whom they are continually waging war; for which reason the Helvetii also surpass the rest of the Gauls in valor, as they contend with the Germans in almost daily battles, when they either repel them from their own territories, or themselves wage war on their frontiers. One part of these, which it has been said that the Gauls occupy, takes its beginning at the river Rhone ; it is bounded by the river Garonne, the ocean, and the territories of the Belgae; it borders, too, on the side of the Sequani and the Helvetii, upon the river Rhine , and stretches toward the north. From 'Caesar's Conquest of Gaul', Translator. W. A. McDevitte. Translator. W. S. Bohn. 1st Edition. New York. Harper & Brothers. 1869. Harper's New Classical Library. Published under creative commons and available at http://www.perseus.tufts.edu/hopper/text?doc=Perseus:text:1999.02.0001"};
int GetFrequency(char*, int*);
void DisplayVHist(int*, int);
我的alphaStats.c源文件:
int GetFrequency(char *pAr, int *pABStats) {
int counter, chNum = 0, i;
char ch = 'A';
for (*pAr = pABStats; *pAr != '\0'; *pAr++) {
chNum = isalpha(*pAr) ? (toascii(toupper(*pAr)) - ch++) : -1;
if (*pAr == chNum)
counter++;
}
printf("%d", chNum);
}
void DisplayVHist(int *pABStats, int size) {
}
我的目标是使用C指针(* pAr和* pABStats)迭代char数组(名为Ar)并打印字母A-Z出现在char数组Ar中的频率。此时我遇到了编写函数GetFrequency()的问题。我理解如何使用带索引的for循环来查找和打印内容,但我是C编程的新手,我在使用指针时遇到了麻烦。
任何帮助都会很棒。提前谢谢。
答案 0 :(得分:1)
需要注意的一点是,在main
函数中,char *pAr = &Ar;
&amp; int *pABStats = &ABStats;
不是你想要的。由于Ar
是字符数组,它是需要分配给指针pAr
的基地址,即char *pAr = Ar
答案 1 :(得分:1)
int GetFrequency(char *pAr, int *pABStats) {
int chNum = 0;
for (; *pAr != '\0'; ++pAr) {
if(isalpha(*pAr)){
chNum = toupper(*pAr) - 'A';
++pABStats[chNum];
}
}
}
int main(void) {
int ABStats[26] = { 0 };
GetFrequency(Ar, ABStats);
return EXIT_SUCCESS;
}