【发布时间】:2020-09-09 16:15:24
【问题描述】:
这是一个从用户那里获取字符串并打印字符串有多少元音和常量的项目。当我为更清晰的代码创建 fanctions malloc_memory 和 free_memory 时,问题就开始了,这样我就可以在 main 中调用函数,而不是直接在 main 函数中分配内存和释放内存。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define E_A_LETTERS 26
#define MAX_LENGTH 50
int check_vowels(char *p_string);
void malloc_memory(char **p_string);
void free_memory(char *p_string);
int main(void){
// Here your code !
char *string;
int vowels;
int constants;
malloc_memory(&string);
printf("Enter a string: ");
fgets(string, MAX_LENGTH, stdin);
vowels = check_vowels(string);
constants = strlen(string) - vowels;
printf("\nNumber of vowels : %d", vowels);
printf("\nNumber of constants : %d\n", constants);
free_memory(string);
}
int check_vowels(char *p_string)
{
int i = 0;
int count = 0;
while(1)
{
if(*(p_string + i) == 'A' || *(p_string + i) == 'E' || *(p_string + i) == 'I' || *(p_string + i) == 'O' || *(p_string + i) == 'U')
count++;
if(*(p_string + i) == 'a' || *(p_string + i) == 'e' || *(p_string + i) == 'i' || *(p_string + i) == 'o' || *(p_string + i) == 'u')
count ++;
if(*(p_string + i) == '\0')
break;
i++;
}
return count;
}
void malloc_memory(char **p_string)
{
p_string = (char **)malloc(MAX_LENGTH * sizeof(char) + 1);
if(p_string == NULL)
{
printf("Unable to allocate memory...");
exit(0);
}
}
void free_memory(char *p_string)
{
free(p_string);
}
我得到这个输出 - 错误:
Enter a string: This is a string
Number of vowels : 4
Number of constants : 12
Segmentation fault (core dumped)
【问题讨论】:
-
当你写“常量的数量”时,你的意思可能是“辅音的数量吗?
-
*(p_string + i)的构造非常常见,有一个更易读的快捷方式:p_string[i]。 -
不,所以目的不是(总是)为您提供现成的解决方案。其目的是帮助您提出解决方案。
-
另外,辅音的数量不正确。仅仅因为一个字符不是元音并不能使它成为辅音。