我正在处理一个涉及IT技术的练习,需要完成以下任务:
- 从用户那里读取20个单词;
- 根据单词长度使用内存分配将它们保存到指针数组中;
- 计算字母频率;
- 使用直方图将其输出。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 20
#define MAX_SIZE 200
int main() {
char *words[N];
int i, c = 0, length;
char *temp;
int freq[26] = { 0 };
temp = (char *)malloc(MAX_SIZE * sizeof(char));
for (i = 0; i < N; i++) {
printf("Give a word:");
gets(temp);
length = strlen(temp);
*(words + i) = (char *)malloc((length + 1) * sizeof(char));
strcpy(*(words + i), temp);
printf("%s\n", *(words + i));
}
free(temp);
while (*words[c] != '\0' && c < 20) {
if ((*words[c] >= 'a' && *words[c] <= 'z') || (*words[c] >= 'A' && *words[c] <= 'Z')) {
freq[*words[c] - 'a']++;
words[c]++;
}
c++;
}
for (i = 0; i < 26; i++) {
printf("%c occurs %d times in the entered string.\n", i + 'a', freq[c]);
}
return 0;
}
*(words + i)
等同于words[i]
吗?虽然两者可以互换使用,但后者通常更受欢迎,因为它真正展示了你正在做什么(索引一个数组)。此外,根据C规范,sizeof(char)
总是返回值1
。 - Some programmer dude