【发布时间】:2021-01-01 10:45:30
【问题描述】:
我有一个函数可以计算字符串中元音和辅音的数量:
void CountVowelsConsonants(char* str, int *vowels, int *consonants){
size_t size=strlen(str);
//size-1 because of the '\n' at the end of the string when pressing enter
for (int i = 0; i < size ; ++i) {
char c = str[i];
if(c=='A' || c== 'E' || c=='I' || c== 'O' || c=='U' ||
c=='a' || c== 'e' || c=='i' || c== 'o' || c=='u'){
*vowels++;
}
}
*consonants= size-1 - *vowels;
}
但是当我调用这个函数时,例如:
int vowels;
int consonants;
CountVowelsConsonants("abc", &vowels, &consonants);
它返回:
Vowels: -858993460
Consonants: 858993463
代替:
Vowels: 1
Consonants: 2
我想知道为什么会这样。
我有一个阶乘函数,它具有类似的指针实现并且可以正常工作:
void factorial(int n, int*fac){
*fac=1;
for (int i = 2; i <= n; ++i) {
*fac*=i;
}
}
在阶乘函数中访问事实指针将正确地改变值。唯一的区别是,在CountVowelsConsonants 函数中,我是递增 1 而不是相乘。
但是,如果我访问 CountVowelsConsonants 函数中的元音指针来增加它会在计数中产生错误。
我的IDE(CLion)会把*vowels中的*变灰,说明里面的指针操作符
*vowels++; 没用。
关于为什么会这样的任何想法?
【问题讨论】:
标签: c loops for-loop pointers parameter-passing